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-7920
Bug: Refactor(routing): Fallback to current active routing algorithm Add connectors from the current active routing algorithm before fallback connectors
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 1b7249cfa44..1c0dd9a3499 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -6475,7 +6475,7 @@ where } if let Some(routing_algorithm) = request_straight_through { - let (mut connectors, check_eligibility) = routing::perform_straight_through_routing( + let (connectors, check_eligibility) = routing::perform_straight_through_routing( &routing_algorithm, payment_data.get_creds_identifier(), ) @@ -6483,57 +6483,34 @@ where .attach_printable("Failed execution of straight through routing")?; if check_eligibility { + let new_pd = payment_data.clone(); let transaction_data = core_routing::PaymentsDslInput::new( - payment_data.get_setup_mandate(), - payment_data.get_payment_attempt(), - payment_data.get_payment_intent(), - payment_data.get_payment_method_data(), - payment_data.get_address(), - payment_data.get_recurring_details(), - payment_data.get_currency(), + new_pd.get_setup_mandate(), + new_pd.get_payment_attempt(), + new_pd.get_payment_intent(), + new_pd.get_payment_method_data(), + new_pd.get_address(), + new_pd.get_recurring_details(), + new_pd.get_currency(), ); - connectors = routing::perform_eligibility_analysis_with_fallback( - &state.clone(), - merchant_context.get_merchant_key_store(), - connectors, - &TransactionData::Payment(transaction_data), - eligible_connectors, + return route_connector_v1_for_payments( + &state, + merchant_context, business_profile, + payment_data, + transaction_data, + routing_data, + eligible_connectors, + mandate_type, + Some(connectors), ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed eligibility analysis and fallback")?; + .await; } - - let connector_data = connectors - .into_iter() - .map(|conn| { - api::ConnectorData::get_connector_by_name( - &state.conf.connectors, - &conn.connector.to_string(), - api::GetToken::Connector, - conn.merchant_connector_id.clone(), - ) - }) - .collect::<CustomResult<Vec<_>, _>>() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid connector name received")?; - - return decide_multiplex_connector_for_normal_or_recurring_payment( - &state, - payment_data, - routing_data, - connector_data, - mandate_type, - business_profile.is_connector_agnostic_mit_enabled, - business_profile.is_network_tokenization_enabled, - ) - .await; } if let Some(ref routing_algorithm) = routing_data.routing_info.algorithm { - let (mut connectors, check_eligibility) = routing::perform_straight_through_routing( + let (connectors, check_eligibility) = routing::perform_straight_through_routing( routing_algorithm, payment_data.get_creds_identifier(), ) @@ -6541,53 +6518,30 @@ where .attach_printable("Failed execution of straight through routing")?; if check_eligibility { + let new_pd = payment_data.clone(); let transaction_data = core_routing::PaymentsDslInput::new( - payment_data.get_setup_mandate(), - payment_data.get_payment_attempt(), - payment_data.get_payment_intent(), - payment_data.get_payment_method_data(), - payment_data.get_address(), - payment_data.get_recurring_details(), - payment_data.get_currency(), + new_pd.get_setup_mandate(), + new_pd.get_payment_attempt(), + new_pd.get_payment_intent(), + new_pd.get_payment_method_data(), + new_pd.get_address(), + new_pd.get_recurring_details(), + new_pd.get_currency(), ); - connectors = routing::perform_eligibility_analysis_with_fallback( + return route_connector_v1_for_payments( &state, - merchant_context.get_merchant_key_store(), - connectors, - &TransactionData::Payment(transaction_data), - eligible_connectors, + merchant_context, business_profile, + payment_data, + transaction_data, + routing_data, + eligible_connectors, + mandate_type, + Some(connectors), ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed eligibility analysis and fallback")?; + .await; } - - let connector_data = connectors - .into_iter() - .map(|conn| { - api::ConnectorData::get_connector_by_name( - &state.conf.connectors, - &conn.connector.to_string(), - api::GetToken::Connector, - conn.merchant_connector_id, - ) - }) - .collect::<CustomResult<Vec<_>, _>>() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid connector name received")?; - - return decide_multiplex_connector_for_normal_or_recurring_payment( - &state, - payment_data, - routing_data, - connector_data, - mandate_type, - business_profile.is_connector_agnostic_mit_enabled, - business_profile.is_network_tokenization_enabled, - ) - .await; } let new_pd = payment_data.clone(); @@ -6610,6 +6564,7 @@ where routing_data, eligible_connectors, mandate_type, + None, ) .await } @@ -7173,6 +7128,7 @@ pub async fn route_connector_v1_for_payments<F, D>( routing_data: &mut storage::RoutingData, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, + connector_list: Option<Vec<api_models::routing::RoutableConnectorChoice>>, ) -> RouterResult<ConnectorCallType> where F: Send + Clone, @@ -7190,7 +7146,7 @@ where algorithm_ref.algorithm_id }; - let connectors = routing::perform_static_routing_v1( + let mut connectors = routing::perform_static_routing_v1( state, merchant_context.get_merchant_account().get_id(), routing_algorithm_id.as_ref(), @@ -7200,10 +7156,20 @@ where .await .change_context(errors::ApiErrorResponse::InternalServerError)?; + // adds straight through connectors to the list of connectors in the active routing algorithm + // and perform eligibility analysis on the combined set of connectors + + connectors = connector_list + .map(|mut straight_through_connectors| { + straight_through_connectors.extend(connectors.clone()); + straight_through_connectors + }) + .unwrap_or_else(|| connectors); + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] let payment_attempt = transaction_data.payment_attempt.clone(); - let connectors = routing::perform_eligibility_analysis_with_fallback( + connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), merchant_context.get_merchant_key_store(), connectors, @@ -7385,7 +7351,6 @@ pub async fn route_connector_v1_for_payouts( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; - let first_connector_choice = connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
2025-04-28T11:32:14Z
## 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 modifies critical paths , specifically the `decide_connector` function and the `route_connector_v1_for_payments` function in the payments confirm flow. These changes are made corresponding to a use case for Narvar. In case the connector specified in straight through routing is not eligible, the connectors configured in the active routing rule by the merchant should be added to the list of connectors before the fallback connectors are added to this list. ### 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 PR closes #7920 ## 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)? --> Stripe and Adyen created with credit disabled for stripe 1. Payment Connector Create - Stripe with credit card disabled ``` curl --location 'http://localhost:8080/account/merchant_1747224808/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sdnmIWRnyDu7lgktwcQ*******' \ --data '{ "connector_type": "payment_processor", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "*******", }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "accepted_countries": { "type": "disable_only", "list": [ "HK" ] }, "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "INR" ] } } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` - Adyen with credit card enabled ``` curl --location 'http://localhost:8080/account/merchant_1747224808/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sdnmIWRnyDu7lgktwcQHoLHEy93541YEgitCw********' \ --data '{ "connector_type": "payment_processor", "connector_name": "adyen", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "AQEqhmfxK43MaR1Hw0m/n3Q5qf3*******", "key1": "Jus******", "api_secret": "AQEzgmDBbd+uOlwd9********" }, "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": { "type": "disable_only", "list": [ "HK" ] }, "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "INR", "AED" ] } }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "accepted_countries": { "type": "disable_only", "list": [ "HK" ] }, "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "INR" ] } } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 2. Create Routing Rule ``` curl --location 'http://localhost:8080/routing' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_sdnmIWRnyDu7lgktwcQHoLHEy93541YEgitCwrluXot******' \ --data '{ "profile_id": "pro_czT9ODMwNqYMmO0Uxnrl", "name": "App based", "description": "This is a rule based routing created at Wed, 21 Aug 2024 08:28:31 GMT", "algorithm": { "type": "advanced", "data": { "defaultSelection": { "type": "priority", "data": [] }, "rules": [ { "name": "rule_1", "connectorSelection": { "type": "priority", "data": [ { "connector": "adyen", "merchant_connector_id": "mca_mduR1DRRqZ9LJQweTxxi" } ] }, "statements": [ { "condition": [ { "lhs": "metadata", "comparison": "equal", "value": { "type": "metadata_variant", "value": { "key": "app", "value": "a" } }, "metadata": {} } ], "nested": null } ] } ], "metadata": {} } } }' ``` 3. Activate Routing rule request ``` curl --location --request POST 'http://localhost:8080/routing/routing_X5yMXyw4NPDt91IapIXi/activate' \ --header 'api-key: dev_sdnmIWRnyDu7lgktwcQHoLHEy93541YEgitC****' ``` 4. Payments Create request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sdnmIWRnyDu7lgktwcQHoLHEy93541YEgitC*******' \ --data-raw '{ "amount": 1000, "currency": "USD", "amount_to_capture": 1000, "confirm": false, "profile_id": "pro_czT9ODMwNqYMmO0Uxnrl", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", **"routing": { "type": "single", "data": { "connector": "stripe", "merchant_connector_id": "mca_Dau6dVR2mgr3oNkNEKXb" } },** "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": "03", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "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 }' ``` response ``` { "payment_id": "pay_BMLwyVUwefqz4mtXqJhK", "merchant_id": "merchant_1746679457", "status": "requires_confirmation", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_BMLwyVUwefqz*****", "created": "2025-05-08T05:31:07.782Z", "currency": "USD", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, ..... ``` 5. Payments Confirm request ``` curl --location 'http://localhost:8080/payments/pay_BMLwyVUwefqz4mtXqJhK/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sdnmIWRnyDu7lgktwcQHoLHE*****' \ --data-raw '{ "amount": 1000, "currency": "USD", "amount_to_capture": 1000, "confirm": true, "profile_id": "pro_czT9ODMwNqYMmO0Uxnrl", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", **"routing": { "type": "single", "data": { "connector": "stripe", "merchant_connector_id": "mca_Dau6dVR2mgr3oNkNEKXb" } },** "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": "03", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "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 }' ``` response ``` { "payment_id": "pay_BMLwyVUwefqz4mtXqJhK", "merchant_id": "merchant_1746679457", "status": "failed", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "adyen", "client_secret": "pay_BMLwyVUwefqz4mtXqJhK_se******", "created": "2025-05-08T05:31:07.782Z", "currency": "USD", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, . . . "error_code": "2", "error_message": "Refused", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "credit", "connector_label": null, . . . "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-08T05:31:14.287Z", "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": "DECLINED Expiry Incorrect" } ``` The connector specified in the routing rule was stripe, but the payment was routed to adyen instead since credit was disabled for stripe at the time of payment connector create. The payment failed because the test card details initially added for stripe are not supported by adyen ## 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.114.0
15df5ac651682b4e4403cea3b0ef58fd9a90f0ec
15df5ac651682b4e4403cea3b0ef58fd9a90f0ec
juspay/hyperswitch
juspay__hyperswitch-7918
Bug: Fix: Validation failing in payment method session - confirm when payment_method_subtype is card Endpoint is returning error code 422 with message "Invalid payment_method_type provided"
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index acdc8870285..37c3ade1018 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2947,10 +2947,18 @@ pub fn validate_payment_method_type_against_payment_method( payment_method_type: api_enums::PaymentMethodType, ) -> bool { match payment_method { + #[cfg(feature = "v1")] api_enums::PaymentMethod::Card => matches!( payment_method_type, api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit ), + #[cfg(feature = "v2")] + api_enums::PaymentMethod::Card => matches!( + payment_method_type, + api_enums::PaymentMethodType::Credit + | api_enums::PaymentMethodType::Debit + | api_enums::PaymentMethodType::Card + ), api_enums::PaymentMethod::PayLater => matches!( payment_method_type, api_enums::PaymentMethodType::Affirm
2025-04-28T10:14:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> In the helper function `validate_payment_method_type_against_payment_method` added `Card` as a valid `PaymentMethodType` when `PaymentMethod` is `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). --> We need to support `card` as a `payment_method_subtype` ## 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/payment-methods-session/12345_pms_01967bcef78f75a08017231cb1264185/confirm' \ --header 'x-profile-id: pro_tvEpY9HoDhpoef5zuFhB' \ --header 'Authorization: publishable-key=pk_dev_cebd8389548b40edba3e0046680b54e8,client-secret=cs_01967bcef78f75a08017232bf96065e5' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_3Je4VFrKJME1ETnyOu3TSzTSfwEz6lTef5BzJkeIWQFeZHhxzfa8KE1gZ0zDApCR' \ --data '{ "payment_method_data": { "card": { "card_number": "4000056655665556", "card_exp_month": "06", "card_exp_year": "25", "card_holder_name": "Hyperswitch", "card_cvc": "123" } }, "payment_method_type": "card", "payment_method_subtype": "card" }' ``` Response: ```json { "id": "12345_pms_01967bcef78f75a08017231cb1264185", "customer_id": "12345_cus_01967bcee4b87d0197fd5aa532ed7703", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "psp_tokenization": { "tokenization_type": "multi_use", "connector_id": "mca_ugK10PaJlQ4K6hxDx8SB" }, "network_tokenization": null, "expires_at": "2025-04-28T10:06:23.536Z", "client_secret": "CLIENT_SECRET_REDACTED", "return_url": null, "next_action": null, "authentication_details": { "status": "succeeded", "error": null }, "associated_payment_methods": 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.113.0
5d26b85639913c1d9b9f3d26fe92c2bb3bc0a2a1
5d26b85639913c1d9b9f3d26fe92c2bb3bc0a2a1
juspay/hyperswitch
juspay__hyperswitch-7912
Bug: [FEATURE] : [CONNECTOR] Add paypal, trustpay, nomupay in feature matrix Add paypal, trustpay, nomupay in feature matrix
diff --git a/config/config.example.toml b/config/config.example.toml index 023298e9571..6b10aadfc87 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -703,6 +703,21 @@ duit_now = { country = "MY", currency = "MYR" } [pm_filters.trustpay] instant_bank_transfer = { country = "CZ,SK,GB,AT,DE,IT", currency = "CZK, EUR, GBP" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,GB", currency = "EUR" } +credit={currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF"} +debit={currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF"} +eps={country="AT", currency="EUR"} +ideal={country="AT", currency="EUR"} +sofort={country="NL", currency="EUR"} +blik={country="PL", currency="PLN"} + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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.dlocal] credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"} diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 95a33620544..33a4f6f3345 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -532,6 +532,22 @@ google_pay = { country = "MY", currency = "MYR" } [pm_filters.trustpay] instant_bank_transfer = { country = "CZ,SK,GB,AT,DE,IT", currency = "CZK, EUR, GBP" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,GB", currency = "EUR" } +credit={currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF"} +debit={currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF"} +eps={country="AT", currency="EUR"} +ideal={country="AT", currency="EUR"} +sofort={country="NL", currency="EUR"} +blik={country="PL", currency="PLN"} + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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.dlocal] credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"} diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 67cdb439c13..e21797fd52e 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -547,6 +547,22 @@ google_pay = { country = "MY", currency = "MYR" } [pm_filters.trustpay] instant_bank_transfer = { country = "CZ,SK,GB,AT,DE,IT", currency = "CZK, EUR, GBP" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,GB", currency = "EUR" } +credit={currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF"} +debit={currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF"} +eps={country="AT", currency="EUR"} +ideal={country="AT", currency="EUR"} +sofort={country="NL", currency="EUR"} +blik={country="PL", currency="PLN"} + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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.dlocal] credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"} diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 26b10f06857..a3bdb26f5ca 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -547,6 +547,21 @@ google_pay = { country = "MY", currency = "MYR" } [pm_filters.trustpay] instant_bank_transfer = { country = "CZ,SK,GB,AT,DE,IT", currency = "CZK, EUR, GBP" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,GB", currency = "EUR" } +credit={currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF"} +debit={currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF"} +eps={country="AT", currency="EUR"} +ideal={country="AT", currency="EUR"} +sofort={country="NL", currency="EUR"} +blik={country="PL", currency="PLN"} + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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.dlocal] credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"} diff --git a/config/development.toml b/config/development.toml index 7618acce813..171489a75e5 100644 --- a/config/development.toml +++ b/config/development.toml @@ -689,10 +689,23 @@ apple_pay = { country = "US", currency = "USD" } ach = { country = "US", currency = "USD" } [pm_filters.trustpay] -credit = { not_available_flows = { capture_method = "manual" } } -debit = { not_available_flows = { capture_method = "manual" } } +credit = { not_available_flows = { capture_method = "manual" }, currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF" } +debit = { not_available_flows = { capture_method = "manual" }, currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF" } instant_bank_transfer = { country = "CZ,SK,GB,AT,DE,IT", currency = "CZK, EUR, GBP" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,GB", currency = "EUR" } +eps={country="AT", currency="EUR"} +ideal={country="AT", currency="EUR"} +sofort={country="NL", currency="EUR"} +blik={country="PL", currency="PLN"} + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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.authorizedotnet] google_pay = { currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 00f5498127c..2f8491b651a 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -650,6 +650,22 @@ duit_now = { country = "MY", currency = "MYR" } [pm_filters.trustpay] instant_bank_transfer = { country = "CZ,SK,GB,AT,DE,IT", currency = "CZK, EUR, GBP" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,GB", currency = "EUR" } +credit={currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF"} +debit={currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF"} +eps={country="AT", currency="EUR"} +ideal={country="AT", currency="EUR"} +sofort={country="NL", currency="EUR"} +blik={country="PL", currency="PLN"} + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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.dlocal] credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"} diff --git a/crates/hyperswitch_connectors/src/connectors/paypal.rs b/crates/hyperswitch_connectors/src/connectors/paypal.rs index 189c012839f..856f1189ea5 100644 --- a/crates/hyperswitch_connectors/src/connectors/paypal.rs +++ b/crates/hyperswitch_connectors/src/connectors/paypal.rs @@ -1,5 +1,6 @@ pub mod transformers; -use std::fmt::Write; + +use std::{fmt::Write, sync::LazyLock}; use base64::Engine; use common_enums::{enums, CallConnectorAction, PaymentAction}; @@ -31,7 +32,8 @@ use hyperswitch_domain_models::{ SetupMandateRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ - PaymentsResponseData, RefundsResponseData, VerifyWebhookSourceResponseData, + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, VerifyWebhookSourceResponseData, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, @@ -361,22 +363,6 @@ impl ConnectorCommon for Paypal { } impl ConnectorValidation for Paypal { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual - | enums::CaptureMethod::SequentialAutomatic => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_implemented_error_report(capture_method, self.id()), - ), - } - } fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, @@ -2174,4 +2160,140 @@ impl ConnectorErrorTypeMapping for Paypal { } } -impl ConnectorSpecifications for Paypal {} +static PAYPAL_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut paypal_supported_payment_methods = SupportedPaymentMethods::new(); + let supported_card_network = vec![ + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::CartesBancaires, + ]; + + paypal_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + paypal_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + paypal_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::Paypal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + paypal_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Eps, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + paypal_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Giropay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + paypal_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Ideal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + paypal_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Sofort, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + paypal_supported_payment_methods +}); + +static PAYPAL_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Paypal", + description: "PayPal is a Slovakia-based company specializing in secure e-commerce payments, particularly within the EEA area.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + +static PAYPAL_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [ + enums::EventClass::Payments, + enums::EventClass::Refunds, + enums::EventClass::Disputes, +]; + +impl ConnectorSpecifications for Paypal { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&PAYPAL_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*PAYPAL_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&PAYPAL_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay.rs b/crates/hyperswitch_connectors/src/connectors/trustpay.rs index 6ae7ee104e1..1c634ac4405 100644 --- a/crates/hyperswitch_connectors/src/connectors/trustpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/trustpay.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use base64::Engine; use common_enums::{enums, PaymentAction}; use common_utils::{ @@ -23,7 +25,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData, @@ -1055,4 +1060,158 @@ impl utils::ConnectorErrorTypeMapping for Trustpay { } } -impl ConnectorSpecifications for Trustpay {} +static TRUSTPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = Vec::new(); + + let mut trustpay_supported_payment_methods = SupportedPaymentMethods::new(); + let supported_card_network = vec![ + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + ]; + + trustpay_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(), + } + }), + ), + }, + ); + + trustpay_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(), + } + }), + ), + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Giropay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Eps, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Ideal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Sofort, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Blik, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::SepaBankTransfer, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + trustpay_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::InstantBankTransfer, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + trustpay_supported_payment_methods + }); + +static TRUSTPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Trustpay", + description: "TrustPay is a Slovakia-based company specializing in secure e-commerce payments, particularly within the EEA area.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + +static TRUSTPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [ + enums::EventClass::Payments, + enums::EventClass::Refunds, + enums::EventClass::Disputes, +]; + +impl ConnectorSpecifications for Trustpay { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&TRUSTPAY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*TRUSTPAY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&TRUSTPAY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 225947be11e..57fa62f6c2e 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -306,6 +306,22 @@ open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,M [pm_filters.trustpay] instant_bank_transfer = { country = "CZ,SK,GB,AT,DE,IT", currency = "CZK, EUR, GBP" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,GB", currency = "EUR" } +credit={currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF"} +debit={currency="EUR,GBP,USD,CAD,AUD,SEK,NOK,DKK,PLN,CZK,HUF,NZD,RON,CHF"} +eps={country="AT", currency="EUR"} +ideal={country="AT", currency="EUR"} +sofort={country="NL", currency="EUR"} +blik={country="PL", currency="PLN"} + +[pm_filters.paypal] +credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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" } +debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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,CG,DO,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,AU,AT,AZ,BS,BH,BB,BY,BE,BZ,BM,BT,BO,BA,BW,BR,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,TD,CL,CO,KM,CG,CD,CK,CR,CI,HR,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,ER,EE,FO,FJ,FI,FR,GF,PF,GA,GM,GE,DE,GI,GR,GL,GD,GP,GT,GN,GW,GY,HN,HK,HU,IS,IN,ID,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KW,KG,LA,LV,LS,LI,LT,LU,MK,MG,MW,MY,MV,ML,MT,MH,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,NO,OM,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,KR,ES,LK,SH,KN,LC,PM,VC,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TG,TO,TT,TN,TM,TC,TV,UG,UA,AE,GB,US,UY,VE,VN", 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.razorpay] upi_collect = { country = "IN", currency = "INR" }
2025-04-27T12:10:53Z
## 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 paypal, trustpay, nomupay connectors in feature matrix ### 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/feature_matrix' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jQNBYCfN5R0473yldj23Yl7HsGbCctexthWkELSAMAGpjCxKAspb2fcQDP1KmMJz' ``` Response: ``` { "connector_count": 2, "connectors": [ { "name": "PAYPAL", "display_name": "Paypal", "description": "PayPal is a Slovakia-based company specializing in secure e-commerce payments, particularly within the EEA area.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "DinersClub", "Discover", "Interac", "JCB", "CartesBancaires" ], "supported_countries": [ "TTO", "HND", "TWN", "DEU", "MCO", "BDI", "SLV", "LCA", "ESP", "GUF", "MUS", "FRO", "FIN", "MKD", "SPM", "ETH", "DNK", "NGA", "GMB", "VCT", "ROU", "QAT", "PER", "MYT", "TGO", "NOR", "TCD", "KNA", "DMA", "FJI", "POL", "KOR", "SLE", "KIR", "LAO", "BFA", "KWT", "CRI", "WSM", "ABW", "GBR", "MWI", "BHR", "ZWE", "BRB", "MSR", "BIH", "SYC", "TZA", "NIU", "COD", "SMR", "KAZ", "NAM", "BMU", "CHL", "ISL", "LKA", "NRU", "BLZ", "GTM", "ZMB", "SGP", "ARE", "GIB", "LSO", "SUR", "GAB", "JPN", "PAN", "CHE", "NCL", "USA", "SVK", "GRD", "DOM", "SAU", "TKM", "UGA", "BLR", "VNM", "MDV", "CYP", "LTU", "LIE", "MAR", "SWZ", "MHL", "ERI", "NER", "MLT", "PNG", "UKR", "SVN", "REU", "NPL", "PYF", "FRA", "NFK", "SHN", "CIV", "ISR", "COG", "SJM", "HKG", "BWA", "URY", "SLB", "BRA", "CPV", "SOM", "GEO", "AGO", "KEN", "MNE", "MOZ", "NIC", "IND", "AUS", "IRL", "CMR", "GRL", "GLP", "LUX", "MEX", "NLD", "THA", "CAN", "HUN", "PCN", "PHL", "TUV", "AIA", "VGB", "PRY", "KHM", "DZA", "GUY", "MNG", "BEL", "TON", "JAM", "TCA", "GNB", "OMN", "ZAF", "COM", "NZL", "MDG", "BRN", "SRB", "IDN", "MLI", "KGZ", "AZE", "VEN", "RWA", "ECU", "GRC", "COK", "DJI", "PRT", "BHS", "EGY", "BTN", "AUT", "RUS", "TUN", "BOL", "MYS", "COL", "SEN", "JOR", "STP", "HRV", "ARG", "FSM", "GIN", "ATG", "MDA", "SWE", "ITA", "LVA", "EST", "BEN", "BGR", "MRT", "CZE", "CYM", "TJK" ], "supported_currencies": [ "PLN", "SEK", "SGD", "BRL", "NZD", "ILS", "CHF", "THB", "PHP", "USD", "CZK", "JPY", "CAD", "CNY", "MXN", "GBP", "HUF", "HKD", "EUR", "MYR", "NOK", "AUD", "DKK", "TWD" ] }, { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "DinersClub", "Discover", "Interac", "JCB", "CartesBancaires" ], "supported_countries": [ "NFK", "URY", "FIN", "NER", "CAN", "GMB", "COM", "SMR", "MCO", "GUF", "DOM", "ECU", "DNK", "CMR", "CRI", "GEO", "BGR", "FRA", "TUN", "GTM", "NLD", "NAM", "PAN", "TCA", "GNB", "SEN", "SVK", "BLZ", "NZL", "AGO", "ATG", "ISR", "MRT", "TON", "OMN", "RUS", "LIE", "BEN", "FJI", "GAB", "SHN", "MLT", "UKR", "TUV", "LTU", "GIN", "RWA", "KHM", "MYS", "VNM", "NGA", "USA", "TWN", "DZA", "MEX", "AUS", "MDV", "SLB", "CHL", "MWI", "ZMB", "BRA", "ZWE", "PCN", "NIU", "GRD", "NOR", "GUY", "BTN", "NRU", "SAU", "SJM", "AZE", "LAO", "GBR", "BHR", "MDG", "IND", "ARG", "EGY", "SGP", "WSM", "HRV", "KAZ", "GIB", "SPM", "GLP", "MDA", "TKM", "STP", "BFA", "BWA", "BEL", "MNE", "ITA", "DJI", "CYP", "KOR", "GRC", "NCL", "KEN", "PER", "VCT", "CHE", "FRO", "KGZ", "AIA", "MYT", "PYF", "CYM", "BRB", "AUT", "ISL", "HKG", "BOL", "PRY", "REU", "IRL", "JPN", "COD", "VGB", "PHL", "SWZ", "EST", "MAR", "JOR", "NIC", "TZA", "ETH", "IDN", "BMU", "SUR", "FSM", "SLE", "ROU", "MNG", "BHS", "PNG", "SOM", "BRN", "NPL", "BDI", "HND", "ARE", "LKA", "MUS", "SLV", "BLR", "POL", "CPV", "JAM", "SYC", "TTO", "MLI", "ZAF", "BIH", "QAT", "LVA", "CZE", "SVN", "KNA", "DEU", "MKD", "DMA", "LUX", "HUN", "ERI", "COG", "COK", "PRT", "THA", "SRB", "GRL", "ABW", "MHL", "SWE", "MOZ", "COL", "TGO", "VEN", "LSO", "TCD", "MSR", "KWT", "KIR", "LCA", "CIV", "UGA", "ESP", "TJK" ], "supported_currencies": [ "CNY", "PHP", "TWD", "HKD", "JPY", "SEK", "MXN", "ILS", "BRL", "PLN", "EUR", "USD", "DKK", "HUF", "AUD", "CAD", "CZK", "NZD", "MYR", "NOK", "GBP", "SGD", "CHF", "THB" ] }, { "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_type_display_name": "PayPal", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "NCL", "MRT", "DMA", "MYS", "GIN", "STP", "MKD", "CAN", "SLV", "ISR", "TTO", "KOR", "KIR", "SMR", "COG", "MLT", "MSR", "KWT", "ITA", "COK", "SLE", "MNG", "MOZ", "FRO", "GRL", "TCD", "DNK", "MWI", "URY", "CPV", "CMR", "MDA", "ESP", "HND", "UKR", "MLI", "AUT", "SGP", "TJK", "DEU", "POL", "SWE", "GUY", "SRB", "KNA", "ETH", "THA", "NPL", "MUS", "PAN", "NIU", "LKA", "VEN", "GLP", "BRB", "OMN", "SWZ", "MDV", "PRT", "LIE", "SUR", "ISL", "LTU", "AZE", "TGO", "FIN", "LSO", "HRV", "PYF", "CHL", "NGA", "BRN", "NZL", "FSM", "LAO", "MYT", "LCA", "BFA", "BTN", "ATG", "CYM", "HKG", "ZMB", "CYP", "SYC", "COL", "AGO", "HUN", "MAR", "CIV", "DOM", "BHR", "SJM", "KGZ", "SOM", "DZA", "EST", "MHL", "PNG", "MCO", "TZA", "GNB", "WSM", "KAZ", "MNE", "QAT", "NAM", "KEN", "COD", "TON", "AIA", "PHL", "TCA", "SEN", "ERI", "JAM", "SHN", "BEN", "GIB", "RUS", "EGY", "BOL", "REU", "ABW", "GMB", "ARG", "VNM", "IND", "LVA", "NOR", "MDG", "GUF", "TUV", "GEO", "TKM", "ARE", "JPN", "VCT", "SAU", "FRA", "GTM", "SVN", "TWN", "LUX", "NRU", "KHM", "BGR", "BMU", "BHS", "ZAF", "NER", "TUN", "PER", "NIC", "UGA", "AUS", "SPM", "BIH", "SLB", "IRL", "COM", "NFK", "BDI", "GRD", "VGB", "GBR", "BLR", "BRA", "PCN", "MEX", "FJI", "GRC", "CHE", "BLZ", "BEL", "IDN", "GAB", "PRY", "ROU", "JOR", "SVK", "NLD", "USA", "DJI", "CRI", "CZE", "BWA", "RWA", "ZWE", "ECU" ], "supported_currencies": [ "GBP", "USD", "ILS", "MYR", "DKK", "CZK", "MXN", "HUF", "SEK", "JPY", "EUR", "HKD", "TWD", "PLN", "SGD", "AUD", "BRL", "PHP", "NOK", "NZD", "CAD", "CHF", "THB", "CNY" ] }, { "payment_method": "bank_redirect", "payment_method_type": "eps", "payment_method_type_display_name": "EPS", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "MDV", "VGB", "COG", "SUR", "LTU", "KGZ", "USA", "BOL", "SRB", "MLI", "GMB", "CAN", "PAN", "GRD", "CYP", "PNG", "RUS", "KWT", "PHL", "CYM", "BTN", "GAB", "TKM", "SVN", "GIN", "AGO", "GUF", "NGA", "COK", "LAO", "BHR", "SJM", "TJK", "BRB", "BEL", "FRO", "SHN", "TCA", "TON", "BLR", "NIU", "MNG", "AIA", "NAM", "KNA", "DOM", "HND", "KOR", "KIR", "MYT", "JAM", "TZA", "ABW", "CRI", "DMA", "PCN", "CZE", "DJI", "IDN", "HRV", "DNK", "IRL", "AUS", "GTM", "ISL", "NPL", "GRC", "THA", "GIB", "LCA", "CHL", "SLV", "AUT", "VEN", "NOR", "MKD", "ZWE", "ECU", "MDA", "GNB", "SWE", "KAZ", "CIV", "FSM", "FRA", "NER", "GLP", "TTO", "ETH", "VCT", "EGY", "NRU", "SWZ", "HUN", "GUY", "NLD", "GRL", "MWI", "JPN", "BGR", "OMN", "BRN", "HKG", "JOR", "NCL", "PER", "DZA", "CMR", "PRY", "MRT", "SYC", "BIH", "BWA", "ITA", "ISR", "SGP", "TWN", "COM", "LIE", "MLT", "MAR", "MEX", "SLB", "MOZ", "NFK", "NZL", "MDG", "FJI", "DEU", "ESP", "KHM", "MSR", "CHE", "GEO", "ARG", "SLE", "ATG", "EST", "PYF", "BRA", "ERI", "SOM", "UGA", "LSO", "SMR", "LKA", "TUN", "GBR", "BHS", "STP", "BEN", "PRT", "IND", "FIN", "MCO", "TGO", "BDI", "MNE", "VNM", "TUV", "TCD", "NIC", "UKR", "URY", "LVA", "QAT", "POL", "SEN", "BMU", "SVK", "MYS", "COD", "RWA", "MHL", "MUS", "ARE", "ZAF", "WSM", "ZMB", "AZE", "BLZ", "KEN", "BFA", "ROU", "SPM", "SAU", "REU", "CPV", "COL", "LUX" ], "supported_currencies": [ "PHP", "SEK", "CAD", "EUR", "BRL", "SGD", "CNY", "NOK", "NZD", "THB", "TWD", "CZK", "GBP", "CHF", "MYR", "JPY", "ILS", "AUD", "MXN", "HUF", "PLN", "USD", "DKK", "HKD" ] }, { "payment_method": "bank_redirect", "payment_method_type": "giropay", "payment_method_type_display_name": "Giropay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "STP", "GRC", "ZMB", "MUS", "CHE", "BRB", "KGZ", "BFA", "TCA", "GMB", "SUR", "MSR", "COL", "DJI", "JOR", "NFK", "WSM", "GAB", "PRY", "GNB", "IND", "MAR", "KEN", "TON", "MLI", "GBR", "LCA", "SGP", "MHL", "MKD", "COG", "BTN", "MDG", "SMR", "AUT", "LIE", "LAO", "FRA", "OMN", "THA", "BGR", "KOR", "REU", "GLP", "CMR", "ABW", "BOL", "MOZ", "HUN", "SPM", "CHL", "TJK", "BRA", "NPL", "COD", "ETH", "TCD", "SVK", "PHL", "AUS", "MDV", "VGB", "CRI", "MDA", "PER", "COK", "CYP", "MEX", "KAZ", "MNG", "RWA", "SWE", "GUF", "BRN", "ISL", "SLE", "TZA", "NIC", "SRB", "RUS", "BLR", "MNE", "MCO", "GUY", "TGO", "NZL", "TKM", "QAT", "SLV", "FJI", "NER", "BIH", "SAU", "TTO", "NOR", "VEN", "TUN", "BEN", "LVA", "EGY", "MRT", "USA", "NCL", "FRO", "IDN", "TWN", "GEO", "SYC", "SVN", "ESP", "VCT", "CAN", "BMU", "ZWE", "EST", "SEN", "ZAF", "MYT", "PAN", "BHR", "PRT", "SJM", "SHN", "CIV", "CYM", "GIN", "KNA", "UGA", "VNM", "BEL", "AGO", "AZE", "LKA", "UKR", "PYF", "GTM", "COM", "JAM", "DEU", "ITA", "MYS", "DOM", "HKG", "ARG", "ECU", "CZE", "DNK", "KHM", "ARE", "GRD", "IRL", "SOM", "CPV", "MLT", "TUV", "MWI", "ROU", "BDI", "ISR", "NIU", "ATG", "FSM", "NAM", "BLZ", "LSO", "NLD", "URY", "BWA", "PNG", "NRU", "KIR", "SLB", "ERI", "FIN", "KWT", "POL", "NGA", "BHS", "AIA", "HRV", "DZA", "DMA", "GIB", "GRL", "HND", "SWZ", "JPN", "LTU", "LUX", "PCN" ], "supported_currencies": [ "PHP", "NZD", "CNY", "GBP", "CHF", "SGD", "USD", "ILS", "BRL", "AUD", "TWD", "PLN", "CZK", "DKK", "EUR", "MYR", "MXN", "CAD", "THB", "NOK", "HKD", "HUF", "JPY", "SEK" ] }, { "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_type_display_name": "iDEAL", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "HRV", "BTN", "MDA", "ESP", "SWE", "NAM", "FRA", "ARG", "PCN", "MNE", "PHL", "LCA", "CMR", "MNG", "ISL", "SAU", "CHE", "FIN", "KIR", "BMU", "GUF", "EGY", "UGA", "SLV", "DJI", "HUN", "GNB", "AZE", "JOR", "BRB", "LKA", "SGP", "THA", "CIV", "TUV", "COK", "SWZ", "SPM", "VNM", "NPL", "CRI", "LVA", "ECU", "GTM", "CPV", "BIH", "COL", "ITA", "HND", "ATG", "RUS", "ZWE", "IRL", "BLR", "NIU", "IND", "MRT", "SEN", "BHS", "TZA", "MSR", "DZA", "PNG", "BWA", "GLP", "ISR", "DNK", "SVK", "TON", "MUS", "CYP", "MEX", "KHM", "KOR", "ERI", "ZAF", "QAT", "BRA", "LUX", "COG", "GBR", "NCL", "TKM", "JPN", "KWT", "FSM", "KEN", "MCO", "PRT", "GRL", "TJK", "BRN", "NOR", "DEU", "LSO", "STP", "GEO", "GIN", "SVN", "VCT", "VGB", "NER", "GRC", "OMN", "KGZ", "COD", "FRO", "KAZ", "FJI", "KNA", "BHR", "EST", "NLD", "TGO", "LAO", "NFK", "REU", "NIC", "UKR", "SJM", "JAM", "GIB", "TTO", "PYF", "BEL", "IDN", "CYM", "BFA", "PRY", "ARE", "BLZ", "COM", "ZMB", "MOZ", "RWA", "SMR", "BDI", "TWN", "CZE", "SYC", "TUN", "MLI", "MYS", "TCA", "MAR", "CAN", "AGO", "SOM", "URY", "ETH", "SHN", "MHL", "GMB", "AUS", "MDG", "GRD", "LTU", "AUT", "NRU", "SLE", "GUY", "NGA", "ROU", "SRB", "MYT", "WSM", "PAN", "NZL", "BOL", "GAB", "DMA", "ABW", "LIE", "TCD", "AIA", "CHL", "SUR", "PER", "BEN", "SLB", "MWI", "MDV", "MKD", "BGR", "VEN", "USA", "MLT", "DOM", "HKG", "POL" ], "supported_currencies": [ "TWD", "USD", "DKK", "MYR", "NOK", "CNY", "MXN", "CZK", "ILS", "CAD", "NZD", "SEK", "CHF", "SGD", "PLN", "PHP", "GBP", "HUF", "EUR", "HKD", "THB", "AUD", "JPY", "BRL" ] }, { "payment_method": "bank_redirect", "payment_method_type": "sofort", "payment_method_type_display_name": "Sofort", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "IRL", "NGA", "MDA", "BRN", "GUY", "RUS", "IND", "BLR", "BMU", "NCL", "MUS", "NOR", "MYT", "KOR", "GNB", "GLP", "GIB", "NIC", "PCN", "SLE", "GBR", "SMR", "COK", "GIN", "THA", "LTU", "TCA", "ESP", "VNM", "TZA", "AIA", "BGR", "COD", "TUN", "TJK", "PYF", "PAN", "NFK", "CHE", "TWN", "BRA", "ISL", "AUS", "PRY", "MWI", "ARE", "KWT", "TUV", "ATG", "SLB", "SLV", "MNE", "FRA", "COM", "CYP", "LVA", "KNA", "HKG", "HUN", "EST", "KGZ", "NPL", "PER", "CYM", "JOR", "URY", "MEX", "SWZ", "TCD", "WSM", "BFA", "MKD", "SOM", "MAR", "SWE", "CZE", "BDI", "GAB", "BIH", "SJM", "DJI", "LUX", "CAN", "GTM", "UKR", "FJI", "KEN", "SUR", "MRT", "REU", "PNG", "ZAF", "NAM", "GUF", "BWA", "GMB", "SVK", "BHR", "GRC", "MNG", "BOL", "JPN", "ECU", "POL", "IDN", "CHL", "SPM", "USA", "TTO", "MHL", "NER", "QAT", "TKM", "VGB", "BEL", "CRI", "KAZ", "MYS", "ABW", "MSR", "LCA", "OMN", "ERI", "SGP", "KIR", "MDG", "VCT", "AGO", "MCO", "NIU", "AUT", "UGA", "MLI", "SYC", "NZL", "DOM", "TON", "DEU", "COG", "ISR", "ZMB", "FSM", "DNK", "STP", "RWA", "LIE", "SAU", "SVN", "ROU", "LSO", "BHS", "VEN", "COL", "TGO", "KHM", "BEN", "NLD", "LAO", "GEO", "AZE", "NRU", "SRB", "CPV", "GRL", "FRO", "SHN", "HND", "EGY", "ZWE", "PRT", "BLZ", "BTN", "HRV", "MLT", "JAM", "ITA", "DZA", "MOZ", "FIN", "CMR", "DMA", "PHL", "MDV", "LKA", "SEN", "ETH", "BRB", "GRD", "CIV", "ARG" ], "supported_currencies": [ "BRL", "ILS", "PHP", "THB", "SGD", "TWD", "CZK", "MXN", "NZD", "NOK", "MYR", "AUD", "GBP", "SEK", "CHF", "HUF", "USD", "DKK", "CNY", "PLN", "HKD", "CAD", "EUR", "JPY" ] } ], "supported_webhook_flows": [ "payments", "refunds", "disputes" ] }, { "name": "TRUSTPAY", "display_name": "Trustpay", "description": "TrustPay is a Slovakia-based company specializing in secure e-commerce payments, particularly within the EEA area.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "DinersClub", "Discover", "Interac", "JCB", "CartesBancaires", "UnionPay" ], "supported_countries": null, "supported_currencies": [ "DKK", "GBP", "NOK", "HUF", "CHF", "USD", "CZK", "AUD", "SEK", "EUR", "CAD", "PLN", "NZD", "RON" ] }, { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "DinersClub", "Discover", "Interac", "JCB", "CartesBancaires", "UnionPay" ], "supported_countries": null, "supported_currencies": [ "NOK", "HUF", "NZD", "CHF", "GBP", "RON", "AUD", "USD", "SEK", "PLN", "EUR", "CAD", "DKK", "CZK" ] }, { "payment_method": "bank_transfer", "payment_method_type": "instant_bank_transfer", "payment_method_type_display_name": "Instant Bank Transfer", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [], "supported_countries": [ "SVK", "AUT", "DEU", "GBR", "ITA", "CZE" ], "supported_currencies": [ "GBP", "EUR", "CZK" ] }, { "payment_method": "bank_transfer", "payment_method_type": "sepa_bank_transfer", "payment_method_type_display_name": "SEPA Bank Transfer", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [], "supported_countries": null, "supported_currencies": null }, { "payment_method": "bank_redirect", "payment_method_type": "giropay", "payment_method_type_display_name": "Giropay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [], "supported_countries": null, "supported_currencies": null }, { "payment_method": "bank_redirect", "payment_method_type": "sofort", "payment_method_type_display_name": "Sofort", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [], "supported_countries": [ "NLD" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "bank_redirect", "payment_method_type": "eps", "payment_method_type_display_name": "EPS", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [], "supported_countries": [ "AUT" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_type_display_name": "iDEAL", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [], "supported_countries": [ "AUT" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "bank_redirect", "payment_method_type": "blik", "payment_method_type_display_name": "BLIK", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [], "supported_countries": [ "POL" ], "supported_currencies": [ "PLN" ] } ], "supported_webhook_flows": [ "payments", "refunds", "disputes" ] }, ] } ``` ## 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.114.0
288da4e43376f4e94521a9c356c9e890d2bf0405
288da4e43376f4e94521a9c356c9e890d2bf0405
juspay/hyperswitch
juspay__hyperswitch-7910
Bug: refactor(connector): [stripebilling] Change BillingConnectorPaymentSync from charges api to payment intents api. Change the url from charge api to stripes payment intent api.
diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs index 3fe121a1fc3..39a8e5a0dae 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs @@ -599,7 +599,7 @@ impl connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( - "{}v1/charges/{}", + "{}v1/payment_intents/{}?expand[0]=latest_charge", self.base_url(connectors), req.request.billing_connector_psync_id )) @@ -632,10 +632,10 @@ impl recovery_router_data_types::BillingConnectorPaymentsSyncRouterData, errors::ConnectorError, > { - let response: stripebilling::StripebillingRecoveryDetailsData = res + let response: stripebilling::StripebillingBillingConnectorPaymentSyncResponseData = res .response - .parse_struct::<stripebilling::StripebillingRecoveryDetailsData>( - "StripebillingRecoveryDetailsData", + .parse_struct::<stripebilling::StripebillingBillingConnectorPaymentSyncResponseData>( + "StripebillingBillingConnectorPaymentSyncResponseData", ) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -807,7 +807,9 @@ impl webhooks::IncomingWebhook for Stripebilling { stripebilling::StripebillingWebhookBody::get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::ConnectorTransactionId(webhook.data.object.charge), + api_models::payments::PaymentIdType::ConnectorTransactionId( + webhook.data.object.payment_intent, + ), )) } diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs index 3ff7d04fde6..1056006642f 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs @@ -296,6 +296,7 @@ pub struct StripebillingWebhookObject { #[serde(rename = "amount_remaining")] pub amount: common_utils::types::MinorUnit, pub charge: String, + pub payment_intent: String, } #[derive(Debug, Serialize, Deserialize)] @@ -346,7 +347,12 @@ impl TryFrom<StripebillingInvoiceBody> for revenue_recovery::RevenueRecoveryInvo } #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct StripebillingRecoveryDetailsData { +pub struct StripebillingBillingConnectorPaymentSyncResponseData { + pub latest_charge: StripebillingLatestChargeData, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct StripebillingLatestChargeData { #[serde(rename = "id")] pub charge_id: String, pub status: StripebillingChargeStatus, @@ -410,7 +416,7 @@ impl TryFrom< ResponseRouterData< recovery_router_flows::BillingConnectorPaymentsSync, - StripebillingRecoveryDetailsData, + StripebillingBillingConnectorPaymentSyncResponseData, recovery_request_types::BillingConnectorPaymentsSyncRequest, recovery_response_types::BillingConnectorPaymentsSyncResponse, >, @@ -420,45 +426,45 @@ impl fn try_from( item: ResponseRouterData< recovery_router_flows::BillingConnectorPaymentsSync, - StripebillingRecoveryDetailsData, + StripebillingBillingConnectorPaymentSyncResponseData, recovery_request_types::BillingConnectorPaymentsSyncRequest, recovery_response_types::BillingConnectorPaymentsSyncResponse, >, ) -> Result<Self, Self::Error> { - let merchant_reference_id = id_type::PaymentReferenceId::from_str( - &item.response.invoice_id, - ) - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "invoice_id", - })?; + let charge_details = item.response.latest_charge; + let merchant_reference_id = + id_type::PaymentReferenceId::from_str(charge_details.invoice_id.as_str()) + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "invoice_id", + })?; let connector_transaction_id = Some(common_utils::types::ConnectorTransactionId::from( - item.response.charge_id, + charge_details.charge_id, )); Ok(Self { response: Ok( recovery_response_types::BillingConnectorPaymentsSyncResponse { - status: item.response.status.into(), - amount: item.response.amount, - currency: item.response.currency, + status: charge_details.status.into(), + amount: charge_details.amount, + currency: charge_details.currency, merchant_reference_id, connector_account_reference_id: MCA_ID_IDENTIFIER_FOR_STRIPE_IN_STRIPEBILLING_MCA_FEAATURE_METADATA .to_string(), connector_transaction_id, - error_code: item.response.failure_code, - error_message: item.response.failure_message, - processor_payment_method_token: item.response.payment_method, - connector_customer_id: item.response.customer, - transaction_created_at: Some(item.response.created), + error_code: charge_details.failure_code, + error_message: charge_details.failure_message, + processor_payment_method_token: charge_details.payment_method, + connector_customer_id: charge_details.customer, + transaction_created_at: Some(charge_details.created), payment_method_sub_type: common_enums::PaymentMethodType::from( - item.response + charge_details .payment_method_details .card_funding_type .funding, ), payment_method_type: common_enums::PaymentMethod::from( - item.response.payment_method_details.type_of_payment_method, + charge_details.payment_method_details.type_of_payment_method, ), }, ),
2025-04-24T12:52:11Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR changes the url of billing connector payment sync flow from using stripe charge api to stripe payment intents api. Because in Recovery Flow there is a chance to call stripe's psync flow to update the error codes and other details for an attempt. And psync flow accepts payment intent id rather than the charge id. To reuse the existing flow we need payment_intent id to propogate. ### 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? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> To test this You can follow the steps of this PR: #7461 Tested it locally. And the logs are as following. <img width="1290" alt="Screenshot 2025-04-24 at 6 10 52 PM" src="https://github.com/user-attachments/assets/7803e047-7ef5-4f58-85a5-f00313f3ab04" /> <img width="1296" alt="Screenshot 2025-04-24 at 6 11 02 PM" src="https://github.com/user-attachments/assets/80049b8e-17fc-40f3-b6ae-d5977ea3ab79" /> <img width="1288" alt="Screenshot 2025-04-24 at 6 10 25 PM" src="https://github.com/user-attachments/assets/cc252496-1924-4e9d-8daa-563c15e85979" /> ## 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.114.0
54e910582fac9bd6fe300a9a96926adf5123403e
54e910582fac9bd6fe300a9a96926adf5123403e
juspay/hyperswitch
juspay__hyperswitch-7916
Bug: Refactor(connector): Migrate [AdyenPlatform, Ebanx, GPayments, Netcetera, Plaid] from crates/router to crates/hyperswitch_connectors Migrate connectors form router crate to hyperswitch_connectors crate
diff --git a/Cargo.lock b/Cargo.lock index 068bb1cecb7..39154406f6e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3877,6 +3877,7 @@ dependencies = [ "strum 0.26.3", "time", "unicode-normalization", + "unidecode", "url", "urlencoding", "uuid", @@ -6551,7 +6552,6 @@ dependencies = [ "totp-rs", "tracing-futures", "unicode-segmentation", - "unidecode", "url", "urlencoding", "utoipa", diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml index b8b74ae272a..d3372b79411 100644 --- a/crates/hyperswitch_connectors/Cargo.toml +++ b/crates/hyperswitch_connectors/Cargo.toml @@ -38,6 +38,7 @@ serde_json = "1.0.115" serde_qs = "0.12.0" serde_repr = "0.1.19" serde_urlencoded = "0.7.1" +unidecode = "0.3.0" serde_with = "3.7.0" sha1 = { version = "0.10.6" } strum = { version = "0.26", features = ["derive"] } diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 80e1253940b..2e5941880e3 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -1,5 +1,6 @@ pub mod aci; pub mod adyen; +pub mod adyenplatform; pub mod airwallex; pub mod amazonpay; pub mod authorizedotnet; @@ -23,6 +24,7 @@ pub mod datatrans; pub mod deutschebank; pub mod digitalvirgo; pub mod dlocal; +pub mod ebanx; pub mod elavon; pub mod facilitapay; pub mod fiserv; @@ -33,6 +35,7 @@ pub mod getnet; pub mod globalpay; pub mod globepay; pub mod gocardless; +pub mod gpayments; pub mod helcim; pub mod hipay; pub mod iatapay; @@ -45,6 +48,7 @@ pub mod mifinity; pub mod mollie; pub mod moneris; pub mod multisafepay; +pub mod netcetera; pub mod nexinets; pub mod nexixpay; pub mod nmi; @@ -62,6 +66,7 @@ pub mod paypal; pub mod paystack; pub mod payu; pub mod placetopay; +pub mod plaid; pub mod powertranz; pub mod prophetpay; pub mod rapyd; @@ -86,25 +91,26 @@ pub mod xendit; pub mod zen; pub mod zsl; pub use self::{ - aci::Aci, adyen::Adyen, airwallex::Airwallex, amazonpay::Amazonpay, - authorizedotnet::Authorizedotnet, bambora::Bambora, bamboraapac::Bamboraapac, - bankofamerica::Bankofamerica, billwerk::Billwerk, bitpay::Bitpay, bluesnap::Bluesnap, - boku::Boku, braintree::Braintree, cashtocode::Cashtocode, chargebee::Chargebee, - checkout::Checkout, coinbase::Coinbase, coingate::Coingate, cryptopay::Cryptopay, - ctp_mastercard::CtpMastercard, cybersource::Cybersource, datatrans::Datatrans, - deutschebank::Deutschebank, digitalvirgo::Digitalvirgo, dlocal::Dlocal, elavon::Elavon, - facilitapay::Facilitapay, fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu, forte::Forte, - getnet::Getnet, globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, - helcim::Helcim, hipay::Hipay, iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, - jpmorgan::Jpmorgan, juspaythreedsserver::Juspaythreedsserver, klarna::Klarna, - mifinity::Mifinity, mollie::Mollie, moneris::Moneris, multisafepay::Multisafepay, - nexinets::Nexinets, nexixpay::Nexixpay, nmi::Nmi, nomupay::Nomupay, noon::Noon, - novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, - payeezy::Payeezy, payme::Payme, payone::Payone, paypal::Paypal, paystack::Paystack, payu::Payu, - placetopay::Placetopay, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, - razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, shift4::Shift4, - square::Square, stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar, thunes::Thunes, - trustpay::Trustpay, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, - volt::Volt, wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, - zen::Zen, zsl::Zsl, + aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex, + amazonpay::Amazonpay, authorizedotnet::Authorizedotnet, bambora::Bambora, + bamboraapac::Bamboraapac, bankofamerica::Bankofamerica, billwerk::Billwerk, bitpay::Bitpay, + bluesnap::Bluesnap, boku::Boku, braintree::Braintree, cashtocode::Cashtocode, + chargebee::Chargebee, checkout::Checkout, coinbase::Coinbase, coingate::Coingate, + cryptopay::Cryptopay, ctp_mastercard::CtpMastercard, cybersource::Cybersource, + datatrans::Datatrans, deutschebank::Deutschebank, digitalvirgo::Digitalvirgo, dlocal::Dlocal, + ebanx::Ebanx, elavon::Elavon, facilitapay::Facilitapay, fiserv::Fiserv, fiservemea::Fiservemea, + fiuu::Fiuu, forte::Forte, getnet::Getnet, globalpay::Globalpay, globepay::Globepay, + gocardless::Gocardless, gpayments::Gpayments, helcim::Helcim, hipay::Hipay, iatapay::Iatapay, + inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, + juspaythreedsserver::Juspaythreedsserver, klarna::Klarna, mifinity::Mifinity, mollie::Mollie, + moneris::Moneris, multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, + nexixpay::Nexixpay, nmi::Nmi, nomupay::Nomupay, noon::Noon, novalnet::Novalnet, nuvei::Nuvei, + opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, + payone::Payone, paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, + plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, + recurly::Recurly, redsys::Redsys, riskified::Riskified, shift4::Shift4, square::Square, + stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar, thunes::Thunes, trustpay::Trustpay, + tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, volt::Volt, + wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen, + zsl::Zsl, }; diff --git a/crates/router/src/connector/adyenplatform.rs b/crates/hyperswitch_connectors/src/connectors/adyenplatform.rs similarity index 55% rename from crates/router/src/connector/adyenplatform.rs rename to crates/hyperswitch_connectors/src/connectors/adyenplatform.rs index ba0dc3d3a2d..9f7b1b77353 100644 --- a/crates/router/src/connector/adyenplatform.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyenplatform.rs @@ -3,8 +3,15 @@ use api_models::{self, webhooks::IncomingWebhookEvent}; #[cfg(feature = "payouts")] use base64::Engine; #[cfg(feature = "payouts")] +use common_utils::crypto; +use common_utils::errors::CustomResult; +#[cfg(feature = "payouts")] +use common_utils::ext_traits::{ByteSliceExt as _, BytesExt}; +#[cfg(feature = "payouts")] use common_utils::request::RequestContent; #[cfg(feature = "payouts")] +use common_utils::request::{Method, Request, RequestBuilder}; +#[cfg(feature = "payouts")] use common_utils::types::MinorUnitForConnector; #[cfg(feature = "payouts")] use common_utils::types::{AmountConvertor, MinorUnit}; @@ -13,35 +20,50 @@ use error_stack::report; use error_stack::ResultExt; #[cfg(feature = "payouts")] use http::HeaderName; -use hyperswitch_interfaces::webhooks::IncomingWebhookFlowError; -use masking::Maskable; #[cfg(feature = "payouts")] -use masking::Secret; +use hyperswitch_domain_models::router_data::{ErrorResponse, RouterData}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::router_flow_types::PoFulfill; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::types::{PayoutsData, PayoutsResponseData, PayoutsRouterData}; +use hyperswitch_domain_models::{ + api::ApplicationResponse, + router_data::{AccessToken, ConnectorAuthType}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, +}; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::events::connector_api_logs::ConnectorEvent; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::types::{PayoutFulfillType, Response}; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorIntegration, ConnectorSpecifications}, + configs::Connectors, + errors::ConnectorError, + webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails}, +}; +use masking::{Mask as _, Maskable, Secret}; #[cfg(feature = "payouts")] use ring::hmac; #[cfg(feature = "payouts")] use router_env::{instrument, tracing}; +#[cfg(feature = "payouts")] +use transformers::get_adyen_webhook_event; use self::transformers as adyenplatform; +use crate::constants::headers; #[cfg(feature = "payouts")] -use crate::connector::utils::convert_amount; -use crate::{ - configs::settings, - core::errors::{self, CustomResult}, - headers, - services::{self, request::Mask, ConnectorSpecifications, ConnectorValidation}, - types::{ - self, - api::{self, ConnectorCommon}, - }, -}; +use crate::types::ResponseRouterData; #[cfg(feature = "payouts")] -use crate::{ - consts, - events::connector_api_logs::ConnectorEvent, - types::transformers::ForeignFrom, - utils::{crypto, ByteSliceExt, BytesExt}, -}; +use crate::utils::convert_amount; #[derive(Clone)] pub struct Adyenplatform { @@ -64,35 +86,34 @@ impl ConnectorCommon for Adyenplatform { fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth = adyenplatform::AdyenplatformAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), )]) } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.adyenplatform.base_url.as_ref() } #[cfg(feature = "payouts")] fn build_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: adyenplatform::AdyenTransferErrorResponse = res .response .parse_struct("AdyenTransferErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response.error_code, message: response.title, @@ -114,92 +135,46 @@ impl api::PaymentCapture for Adyenplatform {} impl api::MandateSetup for Adyenplatform {} impl api::ConnectorAccessToken for Adyenplatform {} impl api::PaymentToken for Adyenplatform {} -impl ConnectorValidation for Adyenplatform {} - -impl - services::ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Adyenplatform -{ -} +impl api::ConnectorValidation for Adyenplatform {} -impl - services::ConnectorIntegration< - api::AccessTokenAuth, - types::AccessTokenRequestData, - types::AccessToken, - > for Adyenplatform +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Adyenplatform { } -impl - services::ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Adyenplatform +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Adyenplatform {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Adyenplatform { } impl api::PaymentSession for Adyenplatform {} -impl - services::ConnectorIntegration< - api::Session, - types::PaymentsSessionData, - types::PaymentsResponseData, - > for Adyenplatform -{ -} +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Adyenplatform {} -impl - services::ConnectorIntegration< - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - > for Adyenplatform -{ -} +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Adyenplatform {} -impl - services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Adyenplatform -{ -} +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Adyenplatform {} -impl - services::ConnectorIntegration< - api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > for Adyenplatform +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> + for Adyenplatform { } -impl - services::ConnectorIntegration< - api::Void, - types::PaymentsCancelData, - types::PaymentsResponseData, - > for Adyenplatform -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Adyenplatform {} impl api::Payouts for Adyenplatform {} #[cfg(feature = "payouts")] impl api::PayoutFulfill for Adyenplatform {} #[cfg(feature = "payouts")] -impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> - for Adyenplatform -{ +impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Adyenplatform { fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!( "{}btl/v4/transfers", connectors.adyenplatform.base_url, @@ -208,17 +183,15 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), - types::PayoutFulfillType::get_content_type(self) - .to_string() - .into(), + PayoutFulfillType::get_content_type(self).to_string().into(), )]; let auth = adyenplatform::AdyenplatformAuthType::try_from(&req.connector_auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; let mut api_key = vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), @@ -229,9 +202,9 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn get_request_body( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, @@ -245,19 +218,15 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn build_request( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutFulfillType::get_headers( - self, req, connectors, - )?) - .set_body(types::PayoutFulfillType::get_request_body( - self, req, connectors, - )?) + .headers(PayoutFulfillType::get_headers(self, req, connectors)?) + .set_body(PayoutFulfillType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) @@ -266,19 +235,19 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P #[instrument(skip_all)] fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoFulfill>, + data: &PayoutsRouterData<PoFulfill>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PayoutsRouterData<PoFulfill>, ConnectorError> { let response: adyenplatform::AdyenTransferResponse = res .response .parse_struct("AdyenTransferResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -287,9 +256,9 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } @@ -298,58 +267,54 @@ impl api::Refund for Adyenplatform {} impl api::RefundExecute for Adyenplatform {} impl api::RefundSync for Adyenplatform {} -impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Adyenplatform -{ -} +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Adyenplatform {} -impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Adyenplatform -{ -} +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Adyenplatform {} #[async_trait::async_trait] -impl api::IncomingWebhook for Adyenplatform { +impl IncomingWebhook for Adyenplatform { #[cfg(feature = "payouts")] fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } #[cfg(feature = "payouts")] fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + ) -> CustomResult<Vec<u8>, ConnectorError> { let base64_signature = request .headers .get(HeaderName::from_static("hmacsignature")) - .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .ok_or(ConnectorError::WebhookSourceVerificationFailed)?; Ok(base64_signature.as_bytes().to_vec()) } #[cfg(feature = "payouts")] fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + ) -> CustomResult<Vec<u8>, ConnectorError> { Ok(request.body.to_vec()) } #[cfg(feature = "payouts")] async fn verify_webhook_source( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, - ) -> CustomResult<bool, errors::ConnectorError> { + ) -> CustomResult<bool, ConnectorError> { + use common_utils::consts; + let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, @@ -357,11 +322,11 @@ impl api::IncomingWebhook for Adyenplatform { connector_webhook_details, ) .await - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let message = self .get_webhook_source_verification_message( @@ -369,10 +334,10 @@ impl api::IncomingWebhook for Adyenplatform { merchant_id, &connector_webhook_secrets, ) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let raw_key = hex::decode(connector_webhook_secrets.secret) - .change_context(errors::ConnectorError::WebhookVerificationSecretInvalid)?; + .change_context(ConnectorError::WebhookVerificationSecretInvalid)?; let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &raw_key); let signed_messaged = hmac::sign(&signing_key, &message); @@ -382,15 +347,15 @@ impl api::IncomingWebhook for Adyenplatform { fn get_webhook_object_reference_id( &self, - #[cfg(feature = "payouts")] request: &api::IncomingWebhookRequestDetails<'_>, - #[cfg(not(feature = "payouts"))] _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + #[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>, + #[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> { #[cfg(feature = "payouts")] { let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request .body .parse_struct("AdyenplatformIncomingWebhook") - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; Ok(api_models::webhooks::ObjectReferenceId::PayoutId( api_models::webhooks::PayoutIdType::PayoutAttemptId(webhook_body.data.reference), @@ -398,18 +363,17 @@ impl api::IncomingWebhook for Adyenplatform { } #[cfg(not(feature = "payouts"))] { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + Err(report!(ConnectorError::WebhooksNotImplemented)) } } fn get_webhook_api_response( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &IncomingWebhookRequestDetails<'_>, error_kind: Option<IncomingWebhookFlowError>, - ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError> - { + ) -> CustomResult<ApplicationResponse<serde_json::Value>, ConnectorError> { if error_kind.is_some() { - Ok(services::api::ApplicationResponse::JsonWithHeaders(( + Ok(ApplicationResponse::JsonWithHeaders(( serde_json::Value::Null, vec![( "x-http-code".to_string(), @@ -417,50 +381,50 @@ impl api::IncomingWebhook for Adyenplatform { )], ))) } else { - Ok(services::api::ApplicationResponse::StatusOk) + Ok(ApplicationResponse::StatusOk) } } fn get_webhook_event_type( &self, - #[cfg(feature = "payouts")] request: &api::IncomingWebhookRequestDetails<'_>, - #[cfg(not(feature = "payouts"))] _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { + #[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>, + #[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { #[cfg(feature = "payouts")] { let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request .body .parse_struct("AdyenplatformIncomingWebhook") - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; - Ok(IncomingWebhookEvent::foreign_from(( + Ok(get_adyen_webhook_event( webhook_body.webhook_type, webhook_body.data.status, webhook_body.data.tracking, - ))) + )) } #[cfg(not(feature = "payouts"))] { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + Err(report!(ConnectorError::WebhooksNotImplemented)) } } fn get_webhook_resource_object( &self, - #[cfg(feature = "payouts")] request: &api::IncomingWebhookRequestDetails<'_>, - #[cfg(not(feature = "payouts"))] _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + #[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>, + #[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { #[cfg(feature = "payouts")] { let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request .body .parse_struct("AdyenplatformIncomingWebhook") - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; Ok(Box::new(webhook_body)) } #[cfg(not(feature = "payouts"))] { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + Err(report!(ConnectorError::WebhooksNotImplemented)) } } } diff --git a/crates/router/src/connector/adyenplatform/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers.rs similarity index 63% rename from crates/router/src/connector/adyenplatform/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers.rs index 20e26c427bf..31d3e77a7fd 100644 --- a/crates/router/src/connector/adyenplatform/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers.rs @@ -1,5 +1,7 @@ use common_utils::types::MinorUnit; use error_stack::Report; +use hyperswitch_domain_models::router_data::ConnectorAuthType; +use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::Serialize; @@ -8,24 +10,22 @@ pub mod payouts; #[cfg(feature = "payouts")] pub use payouts::*; -use crate::{core::errors, types}; - // Error signature -type Error = Report<errors::ConnectorError>; +type Error = Report<ConnectorError>; // Auth Struct pub struct AdyenplatformAuthType { pub(super) api_key: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for AdyenplatformAuthType { +impl TryFrom<&ConnectorAuthType> for AdyenplatformAuthType { type Error = Error; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } @@ -37,7 +37,7 @@ pub struct AdyenPlatformRouterData<T> { } impl<T> TryFrom<(MinorUnit, T)> for AdyenPlatformRouterData<T> { - type Error = Report<errors::ConnectorError>; + type Error = Report<ConnectorError>; fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, diff --git a/crates/router/src/connector/adyenplatform/transformers/payouts.rs b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs similarity index 81% rename from crates/router/src/connector/adyenplatform/transformers/payouts.rs rename to crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs index f3f398760c4..1b1f2b42b77 100644 --- a/crates/router/src/connector/adyenplatform/transformers/payouts.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs @@ -1,18 +1,19 @@ +use api_models::payouts; #[cfg(feature = "payouts")] use api_models::webhooks; +use common_enums::enums; use common_utils::pii; use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::types; +use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::{Deserialize, Serialize}; use super::{AdyenPlatformRouterData, Error}; use crate::{ - connector::{ - adyen::transformers as adyen, - utils::{self, PayoutsData, RouterData}, - }, - core::errors, - types::{self, api::payouts, storage::enums, transformers::ForeignFrom}, + connectors::adyen::transformers as adyen, + types::PayoutsResponseRouterData, + utils::{self, PayoutsData as _, RouterData as _}, }; #[derive(Debug, Default, Serialize, Deserialize)] @@ -24,9 +25,7 @@ impl TryFrom<&Option<pii::SecretSerdeValue>> for AdyenPlatformConnectorMetadataO type Error = Error; fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) - .change_context(errors::ConnectorError::InvalidConnectorConfig { - config: "metadata", - })?; + .change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?; Ok(metadata) } } @@ -182,28 +181,28 @@ impl<F> TryFrom<&AdyenPlatformRouterData<&types::PayoutsRouterData<F>>> for Adye let request = item.router_data.request.to_owned(); match item.router_data.get_payout_method_data()? { payouts::PayoutMethodData::Card(_) | payouts::PayoutMethodData::Wallet(_) => { - Err(errors::ConnectorError::NotImplemented( + Err(ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyenplatform"), ))? } payouts::PayoutMethodData::Bank(bd) => { let bank_details = match bd { - payouts::BankPayout::Sepa(b) => AdyenBankAccountIdentification { + payouts::Bank::Sepa(b) => AdyenBankAccountIdentification { bank_type: "iban".to_string(), account_details: AdyenBankAccountIdentificationDetails::Sepa(SepaDetails { iban: b.iban, }), }, - payouts::BankPayout::Ach(..) => Err(errors::ConnectorError::NotSupported { + payouts::Bank::Ach(..) => Err(ConnectorError::NotSupported { message: "Bank transfer via ACH is not supported".to_string(), connector: "Adyenplatform", })?, - payouts::BankPayout::Bacs(..) => Err(errors::ConnectorError::NotSupported { + payouts::Bank::Bacs(..) => Err(ConnectorError::NotSupported { message: "Bank transfer via Bacs is not supported".to_string(), connector: "Adyenplatform", })?, - payouts::BankPayout::Pix(..) => Err(errors::ConnectorError::NotSupported { + payouts::Bank::Pix(..) => Err(ConnectorError::NotSupported { message: "Bank transfer via Pix is not supported".to_string(), connector: "Adyenplatform", })?, @@ -234,15 +233,14 @@ impl<F> TryFrom<&AdyenPlatformRouterData<&types::PayoutsRouterData<F>>> for Adye )?; let balance_account_id = adyen_connector_metadata_object .source_balance_account - .ok_or(errors::ConnectorError::InvalidConnectorConfig { + .ok_or(ConnectorError::InvalidConnectorConfig { config: "metadata.source_balance_account", })?; - let priority = - request - .priority - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "priority", - })?; + let priority = request + .priority + .ok_or(ConnectorError::MissingRequiredField { + field_name: "priority", + })?; let payout_type = request.get_payout_type()?; Ok(Self { amount: adyen::Amount { @@ -262,12 +260,12 @@ impl<F> TryFrom<&AdyenPlatformRouterData<&types::PayoutsRouterData<F>>> for Adye } } -impl<F> TryFrom<types::PayoutsResponseRouterData<F, AdyenTransferResponse>> +impl<F> TryFrom<PayoutsResponseRouterData<F, AdyenTransferResponse>> for types::PayoutsRouterData<F> { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData<F, AdyenTransferResponse>, + item: PayoutsResponseRouterData<F, AdyenTransferResponse>, ) -> Result<Self, Self::Error> { let response: AdyenTransferResponse = item.response; let status = enums::PayoutStatus::from(response.status); @@ -335,7 +333,7 @@ impl TryFrom<enums::PayoutType> for AdyenPayoutMethod { match payout_type { enums::PayoutType::Bank => Ok(Self::Bank), enums::PayoutType::Card | enums::PayoutType::Wallet => { - Err(report!(errors::ConnectorError::NotSupported { + Err(report!(ConnectorError::NotSupported { message: "Card or wallet payouts".to_string(), connector: "Adyenplatform", })) @@ -398,44 +396,34 @@ pub enum AdyenplatformWebhookStatus { Returned, Received, } - #[cfg(feature = "payouts")] -impl - ForeignFrom<( - AdyenplatformWebhookEventType, - AdyenplatformWebhookStatus, - Option<AdyenplatformInstantStatus>, - )> for webhooks::IncomingWebhookEvent -{ - fn foreign_from( - (event_type, status, instant_status): ( - AdyenplatformWebhookEventType, - AdyenplatformWebhookStatus, - Option<AdyenplatformInstantStatus>, - ), - ) -> Self { - match (event_type, status, instant_status) { - (AdyenplatformWebhookEventType::PayoutCreated, _, _) => Self::PayoutCreated, - (AdyenplatformWebhookEventType::PayoutUpdated, _, Some(instant_status)) => { - match (instant_status.status, instant_status.estimated_arrival_time) { - (Some(InstantPriorityStatus::Credited), _) | (None, Some(_)) => { - Self::PayoutSuccess - } - _ => Self::PayoutProcessing, +pub fn get_adyen_webhook_event( + event_type: AdyenplatformWebhookEventType, + status: AdyenplatformWebhookStatus, + instant_status: Option<AdyenplatformInstantStatus>, +) -> webhooks::IncomingWebhookEvent { + match (event_type, status, instant_status) { + (AdyenplatformWebhookEventType::PayoutCreated, _, _) => { + webhooks::IncomingWebhookEvent::PayoutCreated + } + (AdyenplatformWebhookEventType::PayoutUpdated, _, Some(instant_status)) => { + match (instant_status.status, instant_status.estimated_arrival_time) { + (Some(InstantPriorityStatus::Credited), _) | (None, Some(_)) => { + webhooks::IncomingWebhookEvent::PayoutSuccess } + _ => webhooks::IncomingWebhookEvent::PayoutProcessing, } - (AdyenplatformWebhookEventType::PayoutUpdated, status, _) => match status { - AdyenplatformWebhookStatus::Authorised - | AdyenplatformWebhookStatus::Booked - | AdyenplatformWebhookStatus::Received => Self::PayoutCreated, - AdyenplatformWebhookStatus::Pending => Self::PayoutProcessing, - AdyenplatformWebhookStatus::Failed => Self::PayoutFailure, - AdyenplatformWebhookStatus::Returned => Self::PayoutReversed, - }, } + (AdyenplatformWebhookEventType::PayoutUpdated, status, _) => match status { + AdyenplatformWebhookStatus::Authorised + | AdyenplatformWebhookStatus::Booked + | AdyenplatformWebhookStatus::Received => webhooks::IncomingWebhookEvent::PayoutCreated, + AdyenplatformWebhookStatus::Pending => webhooks::IncomingWebhookEvent::PayoutProcessing, + AdyenplatformWebhookStatus::Failed => webhooks::IncomingWebhookEvent::PayoutFailure, + AdyenplatformWebhookStatus::Returned => webhooks::IncomingWebhookEvent::PayoutReversed, + }, } } - #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenTransferErrorResponse { diff --git a/crates/hyperswitch_connectors/src/connectors/ebanx.rs b/crates/hyperswitch_connectors/src/connectors/ebanx.rs new file mode 100644 index 00000000000..49d5c186426 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/ebanx.rs @@ -0,0 +1,451 @@ +pub mod transformers; + +use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; +#[cfg(feature = "payouts")] +use common_utils::request::RequestContent; +#[cfg(feature = "payouts")] +use common_utils::request::{Method, Request, RequestBuilder}; +#[cfg(feature = "payouts")] +use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}; +use common_utils::{errors::CustomResult, ext_traits::BytesExt}; +use error_stack::{report, ResultExt}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_data::RouterData, + router_flow_types::{PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient}, + types::{PayoutsData, PayoutsResponseData, PayoutsRouterData}, +}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ErrorResponse}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, +}; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::types::{PayoutCancelType, PayoutCreateType, PayoutFulfillType}; +use hyperswitch_interfaces::{ + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + ConnectorValidation, + }, + configs::Connectors, + errors::ConnectorError, + events::connector_api_logs::ConnectorEvent, + types::Response, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +#[cfg(feature = "payouts")] +use masking::Maskable; +#[cfg(feature = "payouts")] +use router_env::{instrument, tracing}; +use transformers as ebanx; + +#[cfg(feature = "payouts")] +use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount}; +#[derive(Clone)] +pub struct Ebanx { + #[cfg(feature = "payouts")] + amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), +} + +impl Ebanx { + pub fn new() -> &'static Self { + &Self { + #[cfg(feature = "payouts")] + amount_converter: &FloatMajorUnitForConnector, + } + } +} + +impl api::Payment for Ebanx {} +impl api::PaymentSession for Ebanx {} +impl api::ConnectorAccessToken for Ebanx {} +impl api::MandateSetup for Ebanx {} +impl api::PaymentAuthorize for Ebanx {} +impl api::PaymentSync for Ebanx {} +impl api::PaymentCapture for Ebanx {} +impl api::PaymentVoid for Ebanx {} +impl api::Refund for Ebanx {} +impl api::RefundExecute for Ebanx {} +impl api::RefundSync for Ebanx {} +impl api::PaymentToken for Ebanx {} + +impl api::Payouts for Ebanx {} +#[cfg(feature = "payouts")] +impl api::PayoutCancel for Ebanx {} +#[cfg(feature = "payouts")] +impl api::PayoutCreate for Ebanx {} +#[cfg(feature = "payouts")] +impl api::PayoutEligibility for Ebanx {} +#[cfg(feature = "payouts")] +impl api::PayoutQuote for Ebanx {} +#[cfg(feature = "payouts")] +impl api::PayoutRecipient for Ebanx {} +#[cfg(feature = "payouts")] +impl api::PayoutFulfill for Ebanx {} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Ebanx +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + #[cfg(feature = "payouts")] + fn build_headers( + &self, + _req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + let header = vec![( + headers::CONTENT_TYPE.to_string(), + self.common_get_content_type().to_string().into(), + )]; + Ok(header) + } +} + +impl ConnectorCommon for Ebanx { + fn id(&self) -> &'static str { + "ebanx" + } + + 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.ebanx.base_url.as_ref() + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + let response: ebanx::EbanxErrorResponse = + res.response + .parse_struct("EbanxErrorResponse") + .change_context(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.status_code, + message: response.code, + reason: response.message, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } +} + +#[cfg(feature = "payouts")] +impl ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for Ebanx { + fn get_url( + &self, + _req: &PayoutsRouterData<PoCreate>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!("{}ws/payout/create", connectors.ebanx.base_url)) + } + + fn get_headers( + &self, + req: &PayoutsRouterData<PoCreate>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_request_body( + &self, + req: &PayoutsRouterData<PoCreate>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.source_currency, + )?; + let connector_router_data = ebanx::EbanxRouterData::from((amount, req)); + let connector_req = ebanx::EbanxPayoutCreateRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PayoutsRouterData<PoCreate>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, 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)?) + .set_body(PayoutCreateType::get_request_body(self, req, connectors)?) + .build(); + + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &PayoutsRouterData<PoCreate>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PayoutsRouterData<PoCreate>, ConnectorError> { + let response: ebanx::EbanxPayoutResponse = res + .response + .parse_struct("EbanxPayoutResponse") + .change_context(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, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "payouts")] +impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Ebanx { + fn get_url( + &self, + _req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!("{}ws/payout/commit", connectors.ebanx.base_url,)) + } + + fn get_headers( + &self, + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_request_body( + &self, + req: &PayoutsRouterData<PoFulfill>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.source_currency, + )?; + let connector_router_data = ebanx::EbanxRouterData::from((amount, req)); + let connector_req = ebanx::EbanxPayoutFulfillRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutFulfillType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PayoutFulfillType::get_headers(self, req, connectors)?) + .set_body(PayoutFulfillType::get_request_body(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>, ConnectorError> { + let response: ebanx::EbanxFulfillResponse = res + .response + .parse_struct("EbanxFulfillResponse") + .change_context(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, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "payouts")] +impl ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> for Ebanx { + fn get_url( + &self, + _req: &PayoutsRouterData<PoCancel>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!("{}ws/payout/cancel", connectors.ebanx.base_url,)) + } + + fn get_headers( + &self, + req: &PayoutsRouterData<PoCancel>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, _connectors) + } + + fn get_request_body( + &self, + req: &PayoutsRouterData<PoCancel>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let connector_req = ebanx::EbanxPayoutCancelRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PayoutsRouterData<PoCancel>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Put) + .url(&PayoutCancelType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PayoutCancelType::get_headers(self, req, connectors)?) + .set_body(PayoutCancelType::get_request_body(self, req, connectors)?) + .build(); + + Ok(Some(request)) + } + + #[instrument(skip_all)] + fn handle_response( + &self, + data: &PayoutsRouterData<PoCancel>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PayoutsRouterData<PoCancel>, ConnectorError> { + let response: ebanx::EbanxCancelResponse = res + .response + .parse_struct("EbanxCancelResponse") + .change_context(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, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "payouts")] +impl ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> for Ebanx {} + +#[cfg(feature = "payouts")] +impl ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData> for Ebanx {} + +#[cfg(feature = "payouts")] +impl ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData> for Ebanx {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Ebanx +{ + // Not Implemented (R) +} + +impl ConnectorValidation for Ebanx { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Ebanx { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Ebanx {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Ebanx {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Ebanx {} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Ebanx {} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Ebanx {} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Ebanx {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Ebanx {} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Ebanx {} + +impl IncomingWebhook for Ebanx { + fn get_webhook_object_reference_id( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) + } +} + +impl ConnectorSpecifications for Ebanx {} diff --git a/crates/router/src/connector/ebanx/transformers.rs b/crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs similarity index 72% rename from crates/router/src/connector/ebanx/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs index f5f096b7307..82e37912560 100644 --- a/crates/router/src/connector/ebanx/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs @@ -3,20 +3,27 @@ use api_models::enums::Currency; #[cfg(feature = "payouts")] use api_models::payouts::{Bank, PayoutMethodData}; #[cfg(feature = "payouts")] +use common_enums::{PayoutStatus, PayoutType}; +#[cfg(feature = "payouts")] use common_utils::pii::Email; use common_utils::types::FloatMajorUnit; +use hyperswitch_domain_models::router_data::ConnectorAuthType; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::router_flow_types::PoCreate; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData}; +use hyperswitch_interfaces::errors::ConnectorError; #[cfg(feature = "payouts")] use masking::ExposeInterface; use masking::Secret; use serde::{Deserialize, Serialize}; #[cfg(feature = "payouts")] -use crate::{ - connector::utils::{AddressDetailsData, RouterData}, - connector::utils::{CustomerDetails, PayoutsData}, - types::{api, storage::enums as storage_enums}, +use crate::types::PayoutsResponseRouterData; +#[cfg(feature = "payouts")] +use crate::utils::{ + AddressDetailsData as _, CustomerDetails as _, PayoutsData as _, RouterData as _, }; -use crate::{core::errors, types}; pub struct EbanxRouterData<T> { pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. @@ -90,13 +97,9 @@ pub enum EbanxBankAccountType { } #[cfg(feature = "payouts")] -impl TryFrom<&EbanxRouterData<&types::PayoutsRouterData<api::PoCreate>>> - for EbanxPayoutCreateRequest -{ - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: &EbanxRouterData<&types::PayoutsRouterData<api::PoCreate>>, - ) -> Result<Self, Self::Error> { +impl TryFrom<&EbanxRouterData<&PayoutsRouterData<PoCreate>>> for EbanxPayoutCreateRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &EbanxRouterData<&PayoutsRouterData<PoCreate>>) -> Result<Self, Self::Error> { let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?; match item.router_data.get_payout_method_data()? { PayoutMethodData::Bank(Bank::Pix(pix_data)) => { @@ -137,7 +140,7 @@ impl TryFrom<&EbanxRouterData<&types::PayoutsRouterData<api::PoCreate>>> }) } PayoutMethodData::Card(_) | PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => { - Err(errors::ConnectorError::NotSupported { + Err(ConnectorError::NotSupported { message: "Payment Method Not Supported".to_string(), connector: "Ebanx", })? @@ -150,14 +153,14 @@ pub struct EbanxAuthType { pub integration_key: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for EbanxAuthType { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { +impl TryFrom<&ConnectorAuthType> for EbanxAuthType { + type Error = error_stack::Report<ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { integration_key: api_key.to_owned(), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } @@ -176,7 +179,7 @@ pub enum EbanxPayoutStatus { } #[cfg(feature = "payouts")] -impl From<EbanxPayoutStatus> for storage_enums::PayoutStatus { +impl From<EbanxPayoutStatus> for PayoutStatus { fn from(item: EbanxPayoutStatus) -> Self { match item { EbanxPayoutStatus::Succeeded => Self::Success, @@ -201,18 +204,14 @@ pub struct EbanxPayoutResponseDetails { } #[cfg(feature = "payouts")] -impl<F> TryFrom<types::PayoutsResponseRouterData<F, EbanxPayoutResponse>> - for types::PayoutsRouterData<F> -{ - type Error = error_stack::Report<errors::ConnectorError>; +impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxPayoutResponse>> for PayoutsRouterData<F> { + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::PayoutsResponseRouterData<F, EbanxPayoutResponse>, + item: PayoutsResponseRouterData<F, EbanxPayoutResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::PayoutsResponseData { - status: Some(storage_enums::PayoutStatus::from( - item.response.payout.status, - )), + response: Ok(PayoutsResponseData { + status: Some(PayoutStatus::from(item.response.payout.status)), connector_payout_id: Some(item.response.payout.uid), payout_eligible: None, should_add_next_step_to_process_tracker: false, @@ -232,26 +231,24 @@ pub struct EbanxPayoutFulfillRequest { } #[cfg(feature = "payouts")] -impl<F> TryFrom<&EbanxRouterData<&types::PayoutsRouterData<F>>> for EbanxPayoutFulfillRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &EbanxRouterData<&types::PayoutsRouterData<F>>) -> Result<Self, Self::Error> { +impl<F> TryFrom<&EbanxRouterData<&PayoutsRouterData<F>>> for EbanxPayoutFulfillRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &EbanxRouterData<&PayoutsRouterData<F>>) -> Result<Self, Self::Error> { let request = item.router_data.request.to_owned(); let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?; let payout_type = request.get_payout_type()?; match payout_type { - storage_enums::PayoutType::Bank => Ok(Self { + PayoutType::Bank => Ok(Self { integration_key: ebanx_auth_type.integration_key, uid: request .connector_payout_id .to_owned() - .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "uid" })?, + .ok_or(ConnectorError::MissingRequiredField { field_name: "uid" })?, }), - storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => { - Err(errors::ConnectorError::NotSupported { - message: "Payout Method Not Supported".to_string(), - connector: "Ebanx", - })? - } + PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotSupported { + message: "Payout Method Not Supported".to_string(), + connector: "Ebanx", + })?, } } } @@ -276,7 +273,7 @@ pub enum EbanxFulfillStatus { } #[cfg(feature = "payouts")] -impl From<EbanxFulfillStatus> for storage_enums::PayoutStatus { +impl From<EbanxFulfillStatus> for PayoutStatus { fn from(item: EbanxFulfillStatus) -> Self { match item { EbanxFulfillStatus::Success => Self::Success, @@ -289,16 +286,14 @@ impl From<EbanxFulfillStatus> for storage_enums::PayoutStatus { } #[cfg(feature = "payouts")] -impl<F> TryFrom<types::PayoutsResponseRouterData<F, EbanxFulfillResponse>> - for types::PayoutsRouterData<F> -{ - type Error = error_stack::Report<errors::ConnectorError>; +impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxFulfillResponse>> for PayoutsRouterData<F> { + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::PayoutsResponseRouterData<F, EbanxFulfillResponse>, + item: PayoutsResponseRouterData<F, EbanxFulfillResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::PayoutsResponseData { - status: Some(storage_enums::PayoutStatus::from(item.response.status)), + response: Ok(PayoutsResponseData { + status: Some(PayoutStatus::from(item.response.status)), connector_payout_id: Some(item.data.request.get_transfer_id()?), payout_eligible: None, should_add_next_step_to_process_tracker: false, @@ -325,26 +320,24 @@ pub struct EbanxPayoutCancelRequest { } #[cfg(feature = "payouts")] -impl<F> TryFrom<&types::PayoutsRouterData<F>> for EbanxPayoutCancelRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { +impl<F> TryFrom<&PayoutsRouterData<F>> for EbanxPayoutCancelRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let ebanx_auth_type = EbanxAuthType::try_from(&item.connector_auth_type)?; let payout_type = request.get_payout_type()?; match payout_type { - storage_enums::PayoutType::Bank => Ok(Self { + PayoutType::Bank => Ok(Self { integration_key: ebanx_auth_type.integration_key, uid: request .connector_payout_id .to_owned() - .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "uid" })?, + .ok_or(ConnectorError::MissingRequiredField { field_name: "uid" })?, }), - storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => { - Err(errors::ConnectorError::NotSupported { - message: "Payout Method Not Supported".to_string(), - connector: "Ebanx", - })? - } + PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotSupported { + message: "Payout Method Not Supported".to_string(), + connector: "Ebanx", + })?, } } } @@ -369,7 +362,7 @@ pub enum EbanxCancelStatus { } #[cfg(feature = "payouts")] -impl From<EbanxCancelStatus> for storage_enums::PayoutStatus { +impl From<EbanxCancelStatus> for PayoutStatus { fn from(item: EbanxCancelStatus) -> Self { match item { EbanxCancelStatus::Success => Self::Cancelled, @@ -382,16 +375,14 @@ impl From<EbanxCancelStatus> for storage_enums::PayoutStatus { } #[cfg(feature = "payouts")] -impl<F> TryFrom<types::PayoutsResponseRouterData<F, EbanxCancelResponse>> - for types::PayoutsRouterData<F> -{ - type Error = error_stack::Report<errors::ConnectorError>; +impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxCancelResponse>> for PayoutsRouterData<F> { + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::PayoutsResponseRouterData<F, EbanxCancelResponse>, + item: PayoutsResponseRouterData<F, EbanxCancelResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::PayoutsResponseData { - status: Some(storage_enums::PayoutStatus::from(item.response.status)), + response: Ok(PayoutsResponseData { + status: Some(PayoutStatus::from(item.response.status)), connector_payout_id: item.data.request.connector_payout_id.clone(), payout_eligible: None, should_add_next_step_to_process_tracker: false, diff --git a/crates/hyperswitch_connectors/src/connectors/gpayments.rs b/crates/hyperswitch_connectors/src/connectors/gpayments.rs new file mode 100644 index 00000000000..85778efd5f6 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/gpayments.rs @@ -0,0 +1,590 @@ +pub mod gpayments_types; +pub mod transformers; + +use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; +use common_utils::{ + errors::CustomResult, + ext_traits::ByteSliceExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, +}; +use error_stack::{report, ResultExt}; +use gpayments_types::GpaymentsConnectorMetaData; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + authentication::{ + Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, + }, + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + authentication::{ + ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, + PreAuthNRequestData, + }, + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{ + AuthenticationResponseData, PaymentsResponseData, RefundsResponseData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + self, + authentication::{ + ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication, + ConnectorPreAuthenticationVersionCall, ExternalAuthentication, + }, + ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + ConnectorValidation, + }, + configs::Connectors, + errors::ConnectorError, + events::connector_api_logs::ConnectorEvent, + types::Response, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +use masking::Maskable; +use transformers as gpayments; + +use crate::{ + constants::headers, + types::{ + ConnectorAuthenticationRouterData, ConnectorAuthenticationType, + ConnectorPostAuthenticationRouterData, ConnectorPostAuthenticationType, + ConnectorPreAuthenticationType, ConnectorPreAuthenticationVersionCallType, + PreAuthNRouterData, PreAuthNVersionCallRouterData, ResponseRouterData, + }, + utils::to_connector_meta, +}; + +#[derive(Clone)] +pub struct Gpayments { + _amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} + +impl Gpayments { + pub fn new() -> &'static Self { + &Self { + _amount_converter: &MinorUnitForConnector, + } + } +} + +impl api::Payment for Gpayments {} +impl api::PaymentSession for Gpayments {} +impl api::ConnectorAccessToken for Gpayments {} +impl api::MandateSetup for Gpayments {} +impl api::PaymentAuthorize for Gpayments {} +impl api::PaymentSync for Gpayments {} +impl api::PaymentCapture for Gpayments {} +impl api::PaymentVoid for Gpayments {} +impl api::Refund for Gpayments {} +impl api::RefundExecute for Gpayments {} +impl api::RefundSync for Gpayments {} +impl api::PaymentToken for Gpayments {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Gpayments +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Gpayments +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + _req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + let header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + Ok(header) + } +} + +impl ConnectorCommon for Gpayments { + fn id(&self) -> &'static str { + "gpayments" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + // 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.gpayments.base_url.as_ref() + } + + fn get_auth_header( + &self, + _auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + Ok(vec![]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + let response: gpayments_types::TDS2ApiError = res + .response + .parse_struct("gpayments_types TDS2ApiError") + .change_context(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.error_code, + message: response.error_description, + reason: response.error_detail, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } +} + +impl ConnectorValidation for Gpayments { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Gpayments {} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Gpayments {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Gpayments +{ +} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Gpayments {} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Gpayments {} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Gpayments {} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Gpayments {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Gpayments {} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Gpayments {} + +#[async_trait::async_trait] +impl IncomingWebhook for Gpayments { + fn get_webhook_object_reference_id( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) + } +} + +impl ExternalAuthentication for Gpayments {} +impl ConnectorAuthentication for Gpayments {} +impl ConnectorPreAuthentication for Gpayments {} +impl ConnectorPreAuthenticationVersionCall for Gpayments {} +impl ConnectorPostAuthentication for Gpayments {} + +fn build_endpoint( + base_url: &str, + connector_metadata: &Option<common_utils::pii::SecretSerdeValue>, +) -> CustomResult<String, ConnectorError> { + let metadata = gpayments::GpaymentsMetaData::try_from(connector_metadata)?; + let endpoint_prefix = metadata.endpoint_prefix; + Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix)) +} + +impl + ConnectorIntegration< + Authentication, + ConnectorAuthenticationRequestData, + AuthenticationResponseData, + > for Gpayments +{ + fn get_headers( + &self, + req: &ConnectorAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &ConnectorAuthenticationRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + let connector_metadata: GpaymentsConnectorMetaData = to_connector_meta( + req.request + .pre_authentication_data + .connector_metadata + .clone(), + )?; + Ok(connector_metadata.authentication_url) + } + + fn get_request_body( + &self, + req: &ConnectorAuthenticationRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req)); + let req_obj = + gpayments_types::GpaymentsAuthenticationRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(req_obj))) + } + fn build_request( + &self, + req: &ConnectorAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&ConnectorAuthenticationType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(ConnectorAuthenticationType::get_headers( + self, req, connectors, + )?) + .set_body(ConnectorAuthenticationType::get_request_body( + self, req, connectors, + )?) + .add_certificate(Some(gpayments_auth_type.certificate)) + .add_certificate_key(Some(gpayments_auth_type.private_key)) + .build(), + )) + } + + fn handle_response( + &self, + data: &ConnectorAuthenticationRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<ConnectorAuthenticationRouterData, ConnectorError> { + let response: gpayments_types::GpaymentsAuthenticationSuccessResponse = res + .response + .parse_struct("gpayments GpaymentsAuthenticationResponse") + .change_context(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, ConnectorError> { + self.build_error_response(res, event_builder) + } +} +impl + ConnectorIntegration< + PostAuthentication, + ConnectorPostAuthenticationRequestData, + AuthenticationResponseData, + > for Gpayments +{ + fn get_headers( + &self, + req: &ConnectorPostAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &ConnectorPostAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; + Ok(format!( + "{}/api/v2/auth/brw/result?threeDSServerTransID={}", + base_url, req.request.threeds_server_transaction_id, + )) + } + + fn build_request( + &self, + req: &ConnectorPostAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&ConnectorPostAuthenticationType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(ConnectorPostAuthenticationType::get_headers( + self, req, connectors, + )?) + .add_certificate(Some(gpayments_auth_type.certificate)) + .add_certificate_key(Some(gpayments_auth_type.private_key)) + .build(), + )) + } + + fn handle_response( + &self, + data: &ConnectorPostAuthenticationRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<ConnectorPostAuthenticationRouterData, ConnectorError> { + let response: gpayments_types::GpaymentsPostAuthenticationResponse = res + .response + .parse_struct("gpayments PaymentsSyncResponse") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ConnectorPostAuthenticationRouterData { + response: Ok(AuthenticationResponseData::PostAuthNResponse { + trans_status: response.trans_status.into(), + authentication_value: response.authentication_value, + eci: response.eci, + }), + ..data.clone() + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData> + for Gpayments +{ + fn get_headers( + &self, + req: &PreAuthNRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &PreAuthNRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; + Ok(format!("{}/api/v2/auth/brw/init?mode=custom", base_url,)) + } + + fn get_request_body( + &self, + req: &PreAuthNRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req)); + let req_obj = + gpayments_types::GpaymentsPreAuthenticationRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(req_obj))) + } + + fn build_request( + &self, + req: &PreAuthNRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&ConnectorPreAuthenticationType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(ConnectorPreAuthenticationType::get_headers( + self, req, connectors, + )?) + .set_body(ConnectorPreAuthenticationType::get_request_body( + self, req, connectors, + )?) + .add_certificate(Some(gpayments_auth_type.certificate)) + .add_certificate_key(Some(gpayments_auth_type.private_key)) + .build(), + )) + } + + fn handle_response( + &self, + data: &PreAuthNRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PreAuthNRouterData, ConnectorError> { + let response: gpayments_types::GpaymentsPreAuthenticationResponse = res + .response + .parse_struct("gpayments GpaymentsPreAuthenticationResponse") + .change_context(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, ConnectorError> { + self.build_error_response(res, event_builder) + } +} +impl + ConnectorIntegration< + PreAuthenticationVersionCall, + PreAuthNRequestData, + AuthenticationResponseData, + > for Gpayments +{ + fn get_headers( + &self, + req: &PreAuthNVersionCallRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &PreAuthNVersionCallRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; + Ok(format!("{}/api/v2/auth/enrol", base_url,)) + } + + fn get_request_body( + &self, + req: &PreAuthNVersionCallRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req)); + let req_obj = + gpayments_types::GpaymentsPreAuthVersionCallRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(req_obj))) + } + + fn build_request( + &self, + req: &PreAuthNVersionCallRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&ConnectorPreAuthenticationVersionCallType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(ConnectorPreAuthenticationVersionCallType::get_headers( + self, req, connectors, + )?) + .set_body(ConnectorPreAuthenticationVersionCallType::get_request_body( + self, req, connectors, + )?) + .add_certificate(Some(gpayments_auth_type.certificate)) + .add_certificate_key(Some(gpayments_auth_type.private_key)) + .build(), + )) + } + + fn handle_response( + &self, + data: &PreAuthNVersionCallRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PreAuthNVersionCallRouterData, ConnectorError> { + let response: gpayments_types::GpaymentsPreAuthVersionCallResponse = res + .response + .parse_struct("gpayments GpaymentsPreAuthVersionCallResponse") + .change_context(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, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorSpecifications for Gpayments {} diff --git a/crates/router/src/connector/gpayments/gpayments_types.rs b/crates/hyperswitch_connectors/src/connectors/gpayments/gpayments_types.rs similarity index 100% rename from crates/router/src/connector/gpayments/gpayments_types.rs rename to crates/hyperswitch_connectors/src/connectors/gpayments/gpayments_types.rs diff --git a/crates/router/src/connector/gpayments/transformers.rs b/crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs similarity index 65% rename from crates/router/src/connector/gpayments/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs index 9acb374c8a8..e959218745f 100644 --- a/crates/router/src/connector/gpayments/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/gpayments/transformers.rs @@ -1,23 +1,36 @@ use api_models::payments::DeviceChannel; use base64::Engine; -use common_utils::{date_time, types::MinorUnit}; +use common_utils::{consts::BASE64_ENGINE, date_time, types::MinorUnit}; use error_stack::ResultExt; +use hyperswitch_domain_models::{ + router_data::{ConnectorAuthType, ErrorResponse}, + router_flow_types::authentication::{ + Authentication, PreAuthentication, PreAuthenticationVersionCall, + }, + router_request_types::{ + authentication::{ + AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData, MessageCategory, + PreAuthNRequestData, + }, + BrowserInformation, + }, + router_response_types::AuthenticationResponseData, +}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::{ExposeInterface, Secret}; use serde::Deserialize; use serde_json::to_string; -use super::gpayments_types; +use super::gpayments_types::{ + self, AuthStatus, BrowserInfoCollected, GpaymentsAuthenticationSuccessResponse, + GpaymentsPreAuthVersionCallResponse, +}; use crate::{ - connector::{ - gpayments::gpayments_types::{ - AuthStatus, BrowserInfoCollected, GpaymentsAuthenticationSuccessResponse, - }, - utils, - utils::{get_card_details, CardData}, + types::{ + ConnectorAuthenticationRouterData, PreAuthNRouterData, PreAuthNVersionCallRouterData, + ResponseRouterData, }, - consts::BASE64_ENGINE, - core::errors, - types::{self, api, api::MessageCategory, authentication::ChallengeParams}, + utils::{get_card_details, to_connector_meta_from_secret, CardData as _}, }; pub struct GpaymentsRouterData<T> { @@ -42,29 +55,29 @@ pub struct GpaymentsAuthType { pub private_key: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for GpaymentsAuthType { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { +impl TryFrom<&ConnectorAuthType> for GpaymentsAuthType { + type Error = error_stack::Report<ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type.to_owned() { - types::ConnectorAuthType::CertificateAuth { + ConnectorAuthType::CertificateAuth { certificate, private_key, } => Ok(Self { certificate, private_key, }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } -impl TryFrom<&GpaymentsRouterData<&types::authentication::PreAuthNVersionCallRouterData>> +impl TryFrom<&GpaymentsRouterData<&PreAuthNVersionCallRouterData>> for gpayments_types::GpaymentsPreAuthVersionCallRequest { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - value: &GpaymentsRouterData<&types::authentication::PreAuthNVersionCallRouterData>, + value: &GpaymentsRouterData<&PreAuthNVersionCallRouterData>, ) -> Result<Self, Self::Error> { let router_data = value.router_data; let metadata = GpaymentsMetaData::try_from(&router_data.connector_meta_data)?; @@ -82,47 +95,43 @@ pub struct GpaymentsMetaData { } impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for GpaymentsMetaData { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( meta_data: &Option<common_utils::pii::SecretSerdeValue>, ) -> Result<Self, Self::Error> { - let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) - .change_context(errors::ConnectorError::InvalidConnectorConfig { - config: "metadata", - })?; + let metadata: Self = to_connector_meta_from_secret::<Self>(meta_data.clone()) + .change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?; Ok(metadata) } } impl TryFrom< - types::ResponseRouterData< - api::PreAuthenticationVersionCall, - gpayments_types::GpaymentsPreAuthVersionCallResponse, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, + ResponseRouterData< + PreAuthenticationVersionCall, + GpaymentsPreAuthVersionCallResponse, + PreAuthNRequestData, + AuthenticationResponseData, >, - > for types::authentication::PreAuthNVersionCallRouterData + > for PreAuthNVersionCallRouterData { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData< - api::PreAuthenticationVersionCall, - gpayments_types::GpaymentsPreAuthVersionCallResponse, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, + item: ResponseRouterData< + PreAuthenticationVersionCall, + GpaymentsPreAuthVersionCallResponse, + PreAuthNRequestData, + AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let version_response = item.response; - let response = Ok( - types::authentication::AuthenticationResponseData::PreAuthVersionCallResponse { - maximum_supported_3ds_version: version_response - .supported_message_versions - .and_then(|supported_version| supported_version.iter().max().cloned()) // if no version is returned for the card number, then - .unwrap_or(common_utils::types::SemanticVersion::new(0, 0, 0)), - }, - ); + let response = Ok(AuthenticationResponseData::PreAuthVersionCallResponse { + maximum_supported_3ds_version: version_response + .supported_message_versions + .and_then(|supported_version| supported_version.iter().max().cloned()) // if no version is returned for the card number, then + .unwrap_or(common_utils::types::SemanticVersion::new(0, 0, 0)), + }); Ok(Self { response, ..item.data.clone() @@ -130,14 +139,12 @@ impl } } -impl TryFrom<&GpaymentsRouterData<&types::authentication::PreAuthNRouterData>> +impl TryFrom<&GpaymentsRouterData<&PreAuthNRouterData>> for gpayments_types::GpaymentsPreAuthenticationRequest { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; - fn try_from( - value: &GpaymentsRouterData<&types::authentication::PreAuthNRouterData>, - ) -> Result<Self, Self::Error> { + fn try_from(value: &GpaymentsRouterData<&PreAuthNRouterData>) -> Result<Self, Self::Error> { let router_data = value.router_data; let metadata = GpaymentsMetaData::try_from(&router_data.connector_meta_data)?; Ok(Self { @@ -154,20 +161,20 @@ impl TryFrom<&GpaymentsRouterData<&types::authentication::PreAuthNRouterData>> } } -impl TryFrom<&GpaymentsRouterData<&types::authentication::ConnectorAuthenticationRouterData>> +impl TryFrom<&GpaymentsRouterData<&ConnectorAuthenticationRouterData>> for gpayments_types::GpaymentsAuthenticationRequest { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: &GpaymentsRouterData<&types::authentication::ConnectorAuthenticationRouterData>, + item: &GpaymentsRouterData<&ConnectorAuthenticationRouterData>, ) -> Result<Self, Self::Error> { let request = &item.router_data.request; let browser_details = match request.browser_details.clone() { - Some(details) => Ok::<Option<types::BrowserInformation>, Self::Error>(Some(details)), + Some(details) => Ok::<Option<BrowserInformation>, Self::Error>(Some(details)), None => { if request.device_channel == DeviceChannel::Browser { - Err(errors::ConnectorError::MissingRequiredField { + Err(ConnectorError::MissingRequiredField { field_name: "browser_info", })? } else { @@ -191,7 +198,7 @@ impl TryFrom<&GpaymentsRouterData<&types::authentication::ConnectorAuthenticatio notification_url: request .return_url .clone() - .ok_or(errors::ConnectorError::RequestEncodingFailed) + .ok_or(ConnectorError::RequestEncodingFailed) .attach_printable("missing return_url")?, three_ds_comp_ind: request.threeds_method_comp_ind.clone(), purchase_amount: item.amount.to_string(), @@ -238,21 +245,21 @@ impl TryFrom<&GpaymentsRouterData<&types::authentication::ConnectorAuthenticatio } impl TryFrom< - types::ResponseRouterData< - api::Authentication, + ResponseRouterData< + Authentication, GpaymentsAuthenticationSuccessResponse, - types::authentication::ConnectorAuthenticationRequestData, - types::authentication::AuthenticationResponseData, + ConnectorAuthenticationRequestData, + AuthenticationResponseData, >, - > for types::authentication::ConnectorAuthenticationRouterData + > for ConnectorAuthenticationRouterData { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData< - api::Authentication, + item: ResponseRouterData< + Authentication, GpaymentsAuthenticationSuccessResponse, - types::authentication::ConnectorAuthenticationRequestData, - types::authentication::AuthenticationResponseData, + ConnectorAuthenticationRequestData, + AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let response_auth = item.response; @@ -264,19 +271,16 @@ impl "challengeWindowSize": "01", }); let creq_str = to_string(&creq) - .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .change_context(ConnectorError::ResponseDeserializationFailed) .attach_printable("error while constructing creq_str")?; let creq_base64 = Engine::encode(&BASE64_ENGINE, creq_str) .trim_end_matches('=') .to_owned(); - let response: Result< - types::authentication::AuthenticationResponseData, - types::ErrorResponse, - > = Ok( - types::authentication::AuthenticationResponseData::AuthNResponse { + let response: Result<AuthenticationResponseData, ErrorResponse> = + Ok(AuthenticationResponseData::AuthNResponse { trans_status: response_auth.trans_status.clone().into(), authn_flow_type: if response_auth.trans_status == AuthStatus::C { - types::authentication::AuthNFlowType::Challenge(Box::new(ChallengeParams { + AuthNFlowType::Challenge(Box::new(ChallengeParams { acs_url: response_auth.acs_url, challenge_request: Some(creq_base64), acs_reference_number: Some(response_auth.acs_reference_number.clone()), @@ -285,13 +289,12 @@ impl acs_signed_content: None, })) } else { - types::authentication::AuthNFlowType::Frictionless + AuthNFlowType::Frictionless }, authentication_value: response_auth.authentication_value, ds_trans_id: Some(response_auth.ds_trans_id), connector_metadata: None, - }, - ); + }); Ok(Self { response, ..item.data.clone() @@ -301,21 +304,21 @@ impl impl TryFrom< - types::ResponseRouterData< - api::PreAuthentication, + ResponseRouterData< + PreAuthentication, gpayments_types::GpaymentsPreAuthenticationResponse, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, + PreAuthNRequestData, + AuthenticationResponseData, >, - > for types::authentication::PreAuthNRouterData + > for PreAuthNRouterData { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData< - api::PreAuthentication, + item: ResponseRouterData< + PreAuthentication, gpayments_types::GpaymentsPreAuthenticationResponse, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, + PreAuthNRequestData, + AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let threeds_method_response = item.response; @@ -328,7 +331,7 @@ impl "threeDSMethodNotificationURL": "https://webhook.site/bd06863d-82c2-42ea-b35b-5ffd5ecece71" }); to_string(&three_ds_method_data_json) - .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .change_context(ConnectorError::ResponseDeserializationFailed) .attach_printable("error while constructing three_ds_method_data_str") .map(|three_ds_method_data_string| { Engine::encode(&BASE64_ENGINE, three_ds_method_data_string) @@ -341,11 +344,8 @@ impl three_ds_requestor_trans_id: None, } )); - let response: Result< - types::authentication::AuthenticationResponseData, - types::ErrorResponse, - > = Ok( - types::authentication::AuthenticationResponseData::PreAuthThreeDsMethodCallResponse { + let response: Result<AuthenticationResponseData, ErrorResponse> = Ok( + AuthenticationResponseData::PreAuthThreeDsMethodCallResponse { threeds_server_transaction_id: threeds_method_response .three_ds_server_trans_id .clone(), diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera.rs b/crates/hyperswitch_connectors/src/connectors/netcetera.rs new file mode 100644 index 00000000000..9a5ecdfd8c3 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/netcetera.rs @@ -0,0 +1,452 @@ +pub mod netcetera_types; +pub mod transformers; + +use std::fmt::Debug; + +use api_models::webhooks::{AuthenticationIdType, IncomingWebhookEvent, ObjectReferenceId}; +use common_utils::{ + errors::CustomResult, + ext_traits::ByteSliceExt, + request::{Method, Request, RequestBuilder, RequestContent}, +}; +use error_stack::ResultExt; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + authentication::{ + Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, + }, + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + authentication::{ + ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, + PreAuthNRequestData, + }, + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{ + AuthenticationResponseData, PaymentsResponseData, RefundsResponseData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + authentication::{ + ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication, + ConnectorPreAuthenticationVersionCall, ExternalAuthentication, + }, + *, + }, + authentication::ExternalAuthenticationPayload, + configs::Connectors, + errors::ConnectorError, + events::connector_api_logs::ConnectorEvent, + types::Response, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +use masking::Maskable; +use transformers as netcetera; + +use crate::{ + constants::headers, + types::{ + ConnectorAuthenticationRouterData, ConnectorAuthenticationType, + ConnectorPreAuthenticationType, PreAuthNRouterData, ResponseRouterData, + }, +}; + +#[derive(Debug, Clone)] +pub struct Netcetera; + +impl Payment for Netcetera {} +impl PaymentSession for Netcetera {} +impl ConnectorAccessToken for Netcetera {} +impl MandateSetup for Netcetera {} +impl PaymentAuthorize for Netcetera {} +impl PaymentSync for Netcetera {} +impl PaymentCapture for Netcetera {} +impl PaymentVoid for Netcetera {} +impl Refund for Netcetera {} +impl RefundExecute for Netcetera {} +impl RefundSync for Netcetera {} +impl PaymentToken for Netcetera {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Netcetera +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Netcetera +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, 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 Netcetera { + fn id(&self) -> &'static str { + "netcetera" + } + + fn get_currency_unit(&self) -> CurrencyUnit { + CurrencyUnit::Minor + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.netcetera.base_url.as_ref() + } + + fn get_auth_header( + &self, + _auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + Ok(vec![]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + let response: netcetera::NetceteraErrorResponse = res + .response + .parse_struct("NetceteraErrorResponse") + .change_context(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.error_details.error_code, + message: response.error_details.error_description, + reason: response.error_details.error_detail, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } +} + +impl ConnectorValidation for Netcetera {} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Netcetera {} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Netcetera {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Netcetera +{ +} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Netcetera {} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Netcetera {} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Netcetera {} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Netcetera {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Netcetera {} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Netcetera {} + +#[async_trait::async_trait] +impl IncomingWebhook for Netcetera { + fn get_webhook_object_reference_id( + &self, + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, ConnectorError> { + let webhook_body: netcetera::ResultsResponseData = request + .body + .parse_struct("netcetera ResultsResponseData") + .change_context(ConnectorError::WebhookBodyDecodingFailed)?; + Ok(ObjectReferenceId::ExternalAuthenticationID( + AuthenticationIdType::ConnectorAuthenticationId(webhook_body.three_ds_server_trans_id), + )) + } + + fn get_webhook_event_type( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { + Ok(IncomingWebhookEvent::ExternalAuthenticationARes) + } + + fn get_webhook_resource_object( + &self, + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { + let webhook_body_value: netcetera::ResultsResponseData = request + .body + .parse_struct("netcetera ResultsResponseDatae") + .change_context(ConnectorError::WebhookBodyDecodingFailed)?; + Ok(Box::new(webhook_body_value)) + } + + fn get_external_authentication_details( + &self, + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ExternalAuthenticationPayload, ConnectorError> { + let webhook_body: netcetera::ResultsResponseData = request + .body + .parse_struct("netcetera ResultsResponseData") + .change_context(ConnectorError::WebhookBodyDecodingFailed)?; + Ok(ExternalAuthenticationPayload { + trans_status: webhook_body + .trans_status + .unwrap_or(common_enums::TransactionStatus::InformationOnly), + authentication_value: webhook_body.authentication_value, + eci: webhook_body.eci, + }) + } +} + +fn build_endpoint( + base_url: &str, + connector_metadata: &Option<common_utils::pii::SecretSerdeValue>, +) -> CustomResult<String, ConnectorError> { + let metadata = netcetera::NetceteraMetaData::try_from(connector_metadata)?; + let endpoint_prefix = metadata.endpoint_prefix; + Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix)) +} + +impl ConnectorPreAuthentication for Netcetera {} +impl ConnectorPreAuthenticationVersionCall for Netcetera {} +impl ExternalAuthentication for Netcetera {} +impl ConnectorAuthentication for Netcetera {} +impl ConnectorPostAuthentication for Netcetera {} + +impl ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData> + for Netcetera +{ + fn get_headers( + &self, + req: &PreAuthNRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &PreAuthNRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; + Ok(format!("{}/3ds/versioning", base_url,)) + } + + fn get_request_body( + &self, + req: &PreAuthNRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let connector_router_data = netcetera::NetceteraRouterData::try_from((0, req))?; + let req_obj = + netcetera::NetceteraPreAuthenticationRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(req_obj))) + } + + fn build_request( + &self, + req: &PreAuthNRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let netcetera_auth_type = netcetera::NetceteraAuthType::try_from(&req.connector_auth_type)?; + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&ConnectorPreAuthenticationType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(ConnectorPreAuthenticationType::get_headers( + self, req, connectors, + )?) + .set_body(ConnectorPreAuthenticationType::get_request_body( + self, req, connectors, + )?) + .add_certificate(Some(netcetera_auth_type.certificate)) + .add_certificate_key(Some(netcetera_auth_type.private_key)) + .build(), + )) + } + + fn handle_response( + &self, + data: &PreAuthNRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PreAuthNRouterData, ConnectorError> { + let response: netcetera::NetceteraPreAuthenticationResponse = res + .response + .parse_struct("netcetera NetceteraPreAuthenticationResponse") + .change_context(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, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl + ConnectorIntegration< + Authentication, + ConnectorAuthenticationRequestData, + AuthenticationResponseData, + > for Netcetera +{ + fn get_headers( + &self, + req: &ConnectorAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &ConnectorAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; + Ok(format!("{}/3ds/authentication", base_url,)) + } + + fn get_request_body( + &self, + req: &ConnectorAuthenticationRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let connector_router_data = netcetera::NetceteraRouterData::try_from(( + &self.get_currency_unit(), + req.request + .currency + .ok_or(ConnectorError::MissingRequiredField { + field_name: "currency", + })?, + req.request + .amount + .ok_or(ConnectorError::MissingRequiredField { + field_name: "amount", + })?, + req, + ))?; + let req_obj = netcetera::NetceteraAuthenticationRequest::try_from(&connector_router_data); + Ok(RequestContent::Json(Box::new(req_obj?))) + } + + fn build_request( + &self, + req: &ConnectorAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let netcetera_auth_type = netcetera::NetceteraAuthType::try_from(&req.connector_auth_type)?; + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&ConnectorAuthenticationType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(ConnectorAuthenticationType::get_headers( + self, req, connectors, + )?) + .set_body(ConnectorAuthenticationType::get_request_body( + self, req, connectors, + )?) + .add_certificate(Some(netcetera_auth_type.certificate)) + .add_certificate_key(Some(netcetera_auth_type.private_key)) + .build(), + )) + } + + fn handle_response( + &self, + data: &ConnectorAuthenticationRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<ConnectorAuthenticationRouterData, ConnectorError> { + let response: netcetera::NetceteraAuthenticationResponse = res + .response + .parse_struct("NetceteraAuthenticationResponse") + .change_context(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, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl + ConnectorIntegration< + PostAuthentication, + ConnectorPostAuthenticationRequestData, + AuthenticationResponseData, + > for Netcetera +{ +} + +impl + ConnectorIntegration< + PreAuthenticationVersionCall, + PreAuthNRequestData, + AuthenticationResponseData, + > for Netcetera +{ +} + +impl ConnectorSpecifications for Netcetera {} diff --git a/crates/router/src/connector/netcetera/netcetera_types.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs similarity index 99% rename from crates/router/src/connector/netcetera/netcetera_types.rs rename to crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs index b79eab200e5..7cd34ec9371 100644 --- a/crates/router/src/connector/netcetera/netcetera_types.rs +++ b/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs @@ -1,12 +1,15 @@ use std::collections::HashMap; use common_utils::{pii::Email, types::SemanticVersion}; -use hyperswitch_connectors::utils::AddressDetailsData; +use hyperswitch_domain_models::router_request_types::{ + authentication::MessageCategory, BrowserInformation, +}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::ExposeInterface; use serde::{Deserialize, Serialize}; use unidecode::unidecode; -use crate::{connector::utils::PhoneDetailsData, errors, types::api::MessageCategory}; +use crate::utils::{AddressDetailsData as _, PhoneDetailsData as _}; #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(untagged)] @@ -367,7 +370,7 @@ pub enum SchemeId { } impl TryFrom<common_enums::CardNetwork> for SchemeId { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from(network: common_enums::CardNetwork) -> Result<Self, Self::Error> { match network { common_enums::CardNetwork::Visa => Ok(Self::Visa), @@ -377,7 +380,7 @@ impl TryFrom<common_enums::CardNetwork> for SchemeId { common_enums::CardNetwork::DinersClub => Ok(Self::Diners), common_enums::CardNetwork::CartesBancaires => Ok(Self::CartesBancaires), common_enums::CardNetwork::UnionPay => Ok(Self::UnionPay), - _ => Err(errors::ConnectorError::RequestEncodingFailedWithReason( + _ => Err(ConnectorError::RequestEncodingFailedWithReason( "Invalid card network".to_string(), ))?, } @@ -768,7 +771,7 @@ impl Option<hyperswitch_domain_models::address::Address>, )> for Cardholder { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( (billing_address, shipping_address): ( hyperswitch_domain_models::address::Address, @@ -880,7 +883,7 @@ pub struct PhoneNumber { } impl TryFrom<hyperswitch_domain_models::address::PhoneDetails> for PhoneNumber { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( value: hyperswitch_domain_models::address::PhoneDetails, ) -> Result<Self, Self::Error> { @@ -1469,8 +1472,8 @@ pub fn get_list_of_accept_languages(accept_language: String) -> Vec<String> { .collect() } -impl From<crate::types::BrowserInformation> for Browser { - fn from(value: crate::types::BrowserInformation) -> Self { +impl From<BrowserInformation> for Browser { + fn from(value: BrowserInformation) -> Self { Self { browser_accept_header: value.accept_header, browser_ip: value diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs similarity index 78% rename from crates/router/src/connector/netcetera/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs index 8e3fb560ceb..467f92b5fdd 100644 --- a/crates/router/src/connector/netcetera/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs @@ -1,13 +1,22 @@ +use common_enums::enums; +use common_utils::{ext_traits::OptionExt as _, types::SemanticVersion}; use error_stack::ResultExt; +use hyperswitch_domain_models::{ + router_data::{ConnectorAuthType, ErrorResponse}, + router_flow_types::authentication::{Authentication, PreAuthentication}, + router_request_types::authentication::{ + AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData, PreAuthNRequestData, + }, + router_response_types::AuthenticationResponseData, +}; +use hyperswitch_interfaces::{api::CurrencyUnit, errors::ConnectorError}; use masking::Secret; use serde::{Deserialize, Serialize}; use super::netcetera_types; use crate::{ - connector::utils::{self, CardData}, - core::errors, - types::{self, api}, - utils::OptionExt, + types::{ConnectorAuthenticationRouterData, PreAuthNRouterData, ResponseRouterData}, + utils::{get_card_details, to_connector_meta_from_secret, CardData as _}, }; //TODO: Fill the struct with respective fields @@ -16,17 +25,10 @@ pub struct NetceteraRouterData<T> { pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)> - for NetceteraRouterData<T> -{ - type Error = error_stack::Report<errors::ConnectorError>; +impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for NetceteraRouterData<T> { + type Error = error_stack::Report<ConnectorError>; fn try_from( - (_currency_unit, _currency, amount, item): ( - &api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (_currency_unit, _currency, amount, item): (&CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { //Todo : use utils to convert the amount to the type of amount that a connector accepts Ok(Self { @@ -37,7 +39,7 @@ impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)> } impl<T> TryFrom<(i64, T)> for NetceteraRouterData<T> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from((amount, router_data): (i64, T)) -> Result<Self, Self::Error> { Ok(Self { amount, @@ -48,21 +50,21 @@ impl<T> TryFrom<(i64, T)> for NetceteraRouterData<T> { impl TryFrom< - types::ResponseRouterData< - api::PreAuthentication, + ResponseRouterData< + PreAuthentication, NetceteraPreAuthenticationResponse, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, + PreAuthNRequestData, + AuthenticationResponseData, >, - > for types::authentication::PreAuthNRouterData + > for PreAuthNRouterData { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData< - api::PreAuthentication, + item: ResponseRouterData< + PreAuthentication, NetceteraPreAuthenticationResponse, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, + PreAuthNRequestData, + AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let response = match item.response { @@ -74,7 +76,7 @@ impl .map(|card_range| card_range.highest_common_supported_version.clone()) .unwrap_or_else(|| { // Version "0.0.0" will be less that "2.0.0", hence we will treat this card as not eligible for 3ds authentication - common_utils::types::SemanticVersion::new(0, 0, 0) + SemanticVersion::new(0, 0, 0) }); let three_ds_method_data = card_range.as_ref().and_then(|card_range| { card_range @@ -85,36 +87,32 @@ impl let three_ds_method_url = card_range .as_ref() .and_then(|card_range| card_range.get_three_ds_method_url()); - Ok( - types::authentication::AuthenticationResponseData::PreAuthNResponse { - threeds_server_transaction_id: pre_authn_response - .three_ds_server_trans_id - .clone(), - maximum_supported_3ds_version: maximum_supported_3ds_version.clone(), - connector_authentication_id: pre_authn_response.three_ds_server_trans_id, - three_ds_method_data, - three_ds_method_url, - message_version: maximum_supported_3ds_version, - connector_metadata: None, - directory_server_id: card_range - .as_ref() - .and_then(|card_range| card_range.directory_server_id.clone()), - }, - ) - } - NetceteraPreAuthenticationResponse::Failure(error_response) => { - Err(types::ErrorResponse { - code: error_response.error_details.error_code, - message: error_response.error_details.error_description, - reason: error_response.error_details.error_detail, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: None, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, + Ok(AuthenticationResponseData::PreAuthNResponse { + threeds_server_transaction_id: pre_authn_response + .three_ds_server_trans_id + .clone(), + maximum_supported_3ds_version: maximum_supported_3ds_version.clone(), + connector_authentication_id: pre_authn_response.three_ds_server_trans_id, + three_ds_method_data, + three_ds_method_url, + message_version: maximum_supported_3ds_version, + connector_metadata: None, + directory_server_id: card_range + .as_ref() + .and_then(|card_range| card_range.directory_server_id.clone()), }) } + NetceteraPreAuthenticationResponse::Failure(error_response) => Err(ErrorResponse { + code: error_response.error_details.error_code, + message: error_response.error_details.error_description, + reason: error_response.error_details.error_detail, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }), }; Ok(Self { response, @@ -125,57 +123,49 @@ impl impl TryFrom< - types::ResponseRouterData< - api::Authentication, + ResponseRouterData< + Authentication, NetceteraAuthenticationResponse, - types::authentication::ConnectorAuthenticationRequestData, - types::authentication::AuthenticationResponseData, + ConnectorAuthenticationRequestData, + AuthenticationResponseData, >, - > for types::authentication::ConnectorAuthenticationRouterData + > for ConnectorAuthenticationRouterData { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData< - api::Authentication, + item: ResponseRouterData< + Authentication, NetceteraAuthenticationResponse, - types::authentication::ConnectorAuthenticationRequestData, - types::authentication::AuthenticationResponseData, + ConnectorAuthenticationRequestData, + AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let response = match item.response { NetceteraAuthenticationResponse::Success(response) => { let authn_flow_type = match response.acs_challenge_mandated { Some(ACSChallengeMandatedIndicator::Y) => { - types::authentication::AuthNFlowType::Challenge(Box::new( - types::authentication::ChallengeParams { - acs_url: response.authentication_response.acs_url.clone(), - challenge_request: response.encoded_challenge_request, - acs_reference_number: response - .authentication_response - .acs_reference_number, - acs_trans_id: response.authentication_response.acs_trans_id, - three_dsserver_trans_id: Some(response.three_ds_server_trans_id), - acs_signed_content: response - .authentication_response - .acs_signed_content, - }, - )) - } - Some(ACSChallengeMandatedIndicator::N) | None => { - types::authentication::AuthNFlowType::Frictionless + AuthNFlowType::Challenge(Box::new(ChallengeParams { + acs_url: response.authentication_response.acs_url.clone(), + challenge_request: response.encoded_challenge_request, + acs_reference_number: response + .authentication_response + .acs_reference_number, + acs_trans_id: response.authentication_response.acs_trans_id, + three_dsserver_trans_id: Some(response.three_ds_server_trans_id), + acs_signed_content: response.authentication_response.acs_signed_content, + })) } + Some(ACSChallengeMandatedIndicator::N) | None => AuthNFlowType::Frictionless, }; - Ok( - types::authentication::AuthenticationResponseData::AuthNResponse { - authn_flow_type, - authentication_value: response.authentication_value, - trans_status: response.trans_status, - connector_metadata: None, - ds_trans_id: response.authentication_response.ds_trans_id, - }, - ) + Ok(AuthenticationResponseData::AuthNResponse { + authn_flow_type, + authentication_value: response.authentication_value, + trans_status: response.trans_status, + connector_metadata: None, + ds_trans_id: response.authentication_response.ds_trans_id, + }) } - NetceteraAuthenticationResponse::Error(error_response) => Err(types::ErrorResponse { + NetceteraAuthenticationResponse::Error(error_response) => Err(ErrorResponse { code: error_response.error_details.error_code, message: error_response.error_details.error_description, reason: error_response.error_details.error_detail, @@ -199,18 +189,18 @@ pub struct NetceteraAuthType { pub(super) private_key: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for NetceteraAuthType { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { +impl TryFrom<&ConnectorAuthType> for NetceteraAuthType { + type Error = error_stack::Report<ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type.to_owned() { - types::ConnectorAuthType::CertificateAuth { + ConnectorAuthType::CertificateAuth { certificate, private_key, } => Ok(Self { certificate, private_key, }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } @@ -269,14 +259,12 @@ pub struct NetceteraMetaData { } impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for NetceteraMetaData { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( meta_data: &Option<common_utils::pii::SecretSerdeValue>, ) -> Result<Self, Self::Error> { - let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) - .change_context(errors::ConnectorError::InvalidConnectorConfig { - config: "metadata", - })?; + let metadata: Self = to_connector_meta_from_secret::<Self>(meta_data.clone()) + .change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?; Ok(metadata) } } @@ -321,7 +309,7 @@ pub struct CardRange { pub acs_protocol_versions: Vec<AcsProtocolVersion>, #[serde(rename = "threeDSMethodDataForm")] pub three_ds_method_data_form: Option<ThreeDSMethodDataForm>, - pub highest_common_supported_version: common_utils::types::SemanticVersion, + pub highest_common_supported_version: SemanticVersion, } impl CardRange { @@ -346,19 +334,15 @@ pub struct ThreeDSMethodDataForm { #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct AcsProtocolVersion { - pub version: common_utils::types::SemanticVersion, + pub version: SemanticVersion, #[serde(rename = "threeDSMethodURL")] pub three_ds_method_url: Option<String>, } -impl TryFrom<&NetceteraRouterData<&types::authentication::PreAuthNRouterData>> - for NetceteraPreAuthenticationRequest -{ - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<&NetceteraRouterData<&PreAuthNRouterData>> for NetceteraPreAuthenticationRequest { + type Error = error_stack::Report<ConnectorError>; - fn try_from( - value: &NetceteraRouterData<&types::authentication::PreAuthNRouterData>, - ) -> Result<Self, Self::Error> { + fn try_from(value: &NetceteraRouterData<&PreAuthNRouterData>) -> Result<Self, Self::Error> { let router_data = value.router_data; let is_cobadged_card = || { router_data @@ -366,7 +350,7 @@ impl TryFrom<&NetceteraRouterData<&types::authentication::PreAuthNRouterData>> .card .card_number .is_cobadged_card() - .change_context(errors::ConnectorError::RequestEncodingFailed) + .change_context(ConnectorError::RequestEncodingFailed) .attach_printable("error while checking is_cobadged_card") }; Ok(Self { @@ -406,7 +390,7 @@ pub struct NetceteraAuthenticationRequest { /// - 2.2.0 -> prefer authentication with 2.2.0 version, /// - 2.3.1 -> prefer authentication with 2.3.1 version, /// - latest -> prefer authentication with the latest version, the 3DS Server is certified for. 2.3.1 at this moment. - pub preferred_protocol_version: Option<common_utils::types::SemanticVersion>, + pub preferred_protocol_version: Option<SemanticVersion>, /// Boolean flag that enforces preferred 3D Secure protocol version to be used in 3D Secure authentication. /// The value should be set true to enforce preferred version. If value is false or not provided, /// 3DS Server can fall back to next supported 3DS protocol version while initiating 3D Secure authentication. @@ -460,12 +444,12 @@ pub struct NetceteraAuthenticationRequest { pub payee_origin: Option<url::Url>, } -impl TryFrom<&NetceteraRouterData<&types::authentication::ConnectorAuthenticationRouterData>> +impl TryFrom<&NetceteraRouterData<&ConnectorAuthenticationRouterData>> for NetceteraAuthenticationRequest { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: &NetceteraRouterData<&types::authentication::ConnectorAuthenticationRouterData>, + item: &NetceteraRouterData<&ConnectorAuthenticationRouterData>, ) -> Result<Self, Self::Error> { let now = common_utils::date_time::now(); let request = item.router_data.request.clone(); @@ -484,12 +468,12 @@ impl TryFrom<&NetceteraRouterData<&types::authentication::ConnectorAuthenticatio .message_version .clone(), ); - let card = utils::get_card_details(request.payment_method_data, "netcetera")?; + let card = get_card_details(request.payment_method_data, "netcetera")?; let is_cobadged_card = card .card_number .clone() .is_cobadged_card() - .change_context(errors::ConnectorError::RequestEncodingFailed) + .change_context(ConnectorError::RequestEncodingFailed) .attach_printable("error while checking is_cobadged_card")?; let cardholder_account = netcetera_types::CardholderAccount { acct_type: None, @@ -511,7 +495,7 @@ impl TryFrom<&NetceteraRouterData<&types::authentication::ConnectorAuthenticatio let currency = request .currency .get_required_value("currency") - .change_context(errors::ConnectorError::MissingRequiredField { + .change_context(ConnectorError::MissingRequiredField { field_name: "currency", })?; let purchase = netcetera_types::Purchase { @@ -526,7 +510,7 @@ impl TryFrom<&NetceteraRouterData<&types::authentication::ConnectorAuthenticatio common_utils::date_time::DateFormat::YYYYMMDDHHmmss, ) .change_context( - errors::ConnectorError::RequestEncodingFailedWithReason( + ConnectorError::RequestEncodingFailedWithReason( "Failed to format Date".to_string(), ), )?, @@ -552,7 +536,7 @@ impl TryFrom<&NetceteraRouterData<&types::authentication::ConnectorAuthenticatio .connector_meta_data .clone() .parse_value("NetceteraMetaData") - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + .change_context(ConnectorError::RequestEncodingFailed)?; let merchant_data = netcetera_types::MerchantData { merchant_configuration_id: connector_meta_data.merchant_configuration_id, mcc: connector_meta_data.mcc, diff --git a/crates/hyperswitch_connectors/src/connectors/plaid.rs b/crates/hyperswitch_connectors/src/connectors/plaid.rs new file mode 100644 index 00000000000..fcd83b380a3 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/plaid.rs @@ -0,0 +1,445 @@ +pub mod transformers; + +use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, +}; +use error_stack::ResultExt; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, PostProcessing, + RSync, Session, SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsPostProcessingData, PaymentsSessionData, + PaymentsSyncData, RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData}, +}; +use hyperswitch_interfaces::{ + api::{ + ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, + ConnectorSpecifications, ConnectorValidation, CurrencyUnit, MandateSetup, Payment, + PaymentAuthorize, PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, + PaymentsPostProcessing, Refund, RefundExecute, RefundSync, + }, + configs::Connectors, + consts::NO_ERROR_CODE, + errors::ConnectorError, + events::connector_api_logs::ConnectorEvent, + types::{PaymentsAuthorizeType, PaymentsPostProcessingType, PaymentsSyncType, Response}, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +use masking::{Mask as _, Maskable}; +use transformers as plaid; + +use crate::{ + constants::headers, + types::{PaymentsPostProcessingRouterData, ResponseRouterData}, + utils::convert_amount, +}; + +#[derive(Clone)] +pub struct Plaid { + amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), +} + +impl Plaid { + pub fn new() -> &'static Self { + &Self { + amount_converter: &FloatMajorUnitForConnector, + } + } +} + +impl Payment for Plaid {} +impl PaymentSession for Plaid {} +impl ConnectorAccessToken for Plaid {} +impl MandateSetup for Plaid {} +impl PaymentAuthorize for Plaid {} +impl PaymentSync for Plaid {} +impl PaymentCapture for Plaid {} +impl PaymentVoid for Plaid {} +impl Refund for Plaid {} +impl RefundExecute for Plaid {} +impl RefundSync for Plaid {} +impl PaymentToken for Plaid {} +impl PaymentsPostProcessing for Plaid {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Plaid +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + let mut auth = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut auth); + Ok(header) + } +} + +impl ConnectorCommon for Plaid { + fn id(&self) -> &'static str { + "plaid" + } + + fn get_currency_unit(&self) -> CurrencyUnit { + CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.plaid.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + let auth = plaid::PlaidAuthType::try_from(auth_type) + .change_context(ConnectorError::FailedToObtainAuthType)?; + let client_id = auth.client_id.into_masked(); + let secret = auth.secret.into_masked(); + + Ok(vec![ + ("PLAID-CLIENT-ID".to_string(), client_id), + ("PLAID-SECRET".to_string(), secret), + ]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + let response: plaid::PlaidErrorResponse = + res.response + .parse_struct("PlaidErrorResponse") + .change_context(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.error_code.unwrap_or(NO_ERROR_CODE.to_string()), + message: response.error_message, + reason: response.display_message, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } +} + +impl ConnectorValidation for Plaid { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Plaid { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Plaid {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Plaid {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Plaid { + fn get_headers( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, 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, ConnectorError> { + Ok(format!( + "{}/payment_initiation/payment/create", + self.base_url(connectors) + )) + } + + fn get_request_body( + &self, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + let connector_router_data = plaid::PlaidRouterData::from((amount, req)); + let connector_req = plaid::PlaidPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, ConnectorError> { + let response: plaid::PlaidPaymentsResponse = res + .response + .parse_struct("PlaidPaymentsResponse") + .change_context(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, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Plaid { + fn get_headers( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_request_body( + &self, + req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let connector_req = plaid::PlaidSyncRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn get_url( + &self, + _req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!( + "{}/payment_initiation/payment/get", + self.base_url(connectors) + )) + } + + fn build_request( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) + .set_body(PaymentsSyncType::get_request_body(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, ConnectorError> { + let response: plaid::PlaidSyncResponse = res + .response + .parse_struct("PlaidSyncResponse") + .change_context(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, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData> + for Plaid +{ + fn get_headers( + &self, + req: &PaymentsPostProcessingRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsPostProcessingRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!("{}/link/token/create", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &PaymentsPostProcessingRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let connector_req = plaid::PlaidLinkTokenRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsPostProcessingRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsPostProcessingType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PaymentsPostProcessingType::get_headers( + self, req, connectors, + )?) + .set_body(PaymentsPostProcessingType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsPostProcessingRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsPostProcessingRouterData, ConnectorError> { + let response: plaid::PlaidLinkTokenResponse = res + .response + .parse_struct("PlaidLinkTokenResponse") + .change_context(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, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Plaid {} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Plaid {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Plaid {} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Plaid {} + +#[async_trait::async_trait] +impl IncomingWebhook for Plaid { + fn get_webhook_object_reference_id( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, ConnectorError> { + Err((ConnectorError::WebhooksNotImplemented).into()) + } + + fn get_webhook_event_type( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { + Err((ConnectorError::WebhooksNotImplemented).into()) + } + + fn get_webhook_resource_object( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { + Err((ConnectorError::WebhooksNotImplemented).into()) + } +} + +impl ConnectorSpecifications for Plaid {} diff --git a/crates/router/src/connector/plaid/transformers.rs b/crates/hyperswitch_connectors/src/connectors/plaid/transformers.rs similarity index 74% rename from crates/router/src/connector/plaid/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/plaid/transformers.rs index da4bc82fca3..40ea49668ab 100644 --- a/crates/router/src/connector/plaid/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/plaid/transformers.rs @@ -1,12 +1,20 @@ -use common_enums::Currency; +use api_models::payments::OpenBankingSessionToken; +use common_enums::{AttemptStatus, Currency}; use common_utils::types::FloatMajorUnit; +use hyperswitch_domain_models::{ + payment_method_data::{OpenBankingData, PaymentMethodData}, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, + router_request_types::ResponseId, + router_response_types::PaymentsResponseData, + types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData}, +}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::is_payment_failure, - core::errors, - types::{self, api, domain, storage::enums}, + types::{PaymentsPostProcessingRouterData, ResponseRouterData}, + utils::is_payment_failure, }; pub struct PlaidRouterData<T> { @@ -86,14 +94,12 @@ pub struct PlaidPaymentInitiation { payment_id: String, } -impl TryFrom<&PlaidRouterData<&types::PaymentsAuthorizeRouterData>> for PlaidPaymentsRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: &PlaidRouterData<&types::PaymentsAuthorizeRouterData>, - ) -> Result<Self, Self::Error> { +impl TryFrom<&PlaidRouterData<&PaymentsAuthorizeRouterData>> for PlaidPaymentsRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &PlaidRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { - domain::PaymentMethodData::OpenBanking(ref data) => match data { - domain::OpenBankingData::OpenBankingPIS { .. } => { + PaymentMethodData::OpenBanking(ref data) => match data { + OpenBankingData::OpenBankingPIS { .. } => { let amount = item.amount; let currency = item.router_data.request.currency; let payment_id = item.router_data.payment_id.clone(); @@ -103,7 +109,7 @@ impl TryFrom<&PlaidRouterData<&types::PaymentsAuthorizeRouterData>> for PlaidPay } else { Some(payment_id) } - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "payment_id", })?; let recipient_type = item @@ -115,7 +121,7 @@ impl TryFrom<&PlaidRouterData<&types::PaymentsAuthorizeRouterData>> for PlaidPay data, ) => data.clone(), }) - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "additional_merchant_data", })?; @@ -123,7 +129,7 @@ impl TryFrom<&PlaidRouterData<&types::PaymentsAuthorizeRouterData>> for PlaidPay api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => { Ok(id.peek().to_string()) } - _ => Err(errors::ConnectorError::MissingRequiredField { + _ => Err(ConnectorError::MissingRequiredField { field_name: "ConnectorRecipientId", }), }?; @@ -140,29 +146,29 @@ impl TryFrom<&PlaidRouterData<&types::PaymentsAuthorizeRouterData>> for PlaidPay }) } }, - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + _ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } -impl TryFrom<&types::PaymentsSyncRouterData> for PlaidSyncRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&PaymentsSyncRouterData> for PlaidSyncRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> { match item.request.connector_transaction_id { - types::ResponseId::ConnectorTransactionId(ref id) => Ok(Self { + ResponseId::ConnectorTransactionId(ref id) => Ok(Self { payment_id: id.clone(), }), - _ => Err((errors::ConnectorError::MissingConnectorTransactionID).into()), + _ => Err((ConnectorError::MissingConnectorTransactionID).into()), } } } -impl TryFrom<&types::PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsPostProcessingRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &PaymentsPostProcessingRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data { - domain::PaymentMethodData::OpenBanking(ref data) => match data { - domain::OpenBankingData::OpenBankingPIS { .. } => { + PaymentMethodData::OpenBanking(ref data) => match data { + OpenBankingData::OpenBankingPIS { .. } => { let headers = item.header_payload.clone(); let platform = headers @@ -181,7 +187,7 @@ impl TryFrom<&types::PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest .request .country .map(|code| vec![code.to_string()]) - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "billing.address.country", })?, language: "en".to_string(), @@ -199,7 +205,7 @@ impl TryFrom<&types::PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest .request .connector_transaction_id .clone() - .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, + .ok_or(ConnectorError::MissingConnectorTransactionID)?, }, android_package_name: if is_android { headers @@ -218,7 +224,7 @@ impl TryFrom<&types::PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest }) } }, - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + _ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } @@ -228,15 +234,15 @@ pub struct PlaidAuthType { pub secret: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { +impl TryFrom<&ConnectorAuthType> for PlaidAuthType { + type Error = error_stack::Report<ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { client_id: api_key.to_owned(), secret: key1.to_owned(), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } @@ -258,7 +264,7 @@ pub enum PlaidPaymentStatus { PaymentStatusAuthorising, } -impl From<PlaidPaymentStatus> for enums::AttemptStatus { +impl From<PlaidPaymentStatus> for AttemptStatus { fn from(item: PlaidPaymentStatus) -> Self { match item { PlaidPaymentStatus::PaymentStatusAuthorising => Self::Authorizing, @@ -282,19 +288,18 @@ pub struct PlaidPaymentsResponse { payment_id: String, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, PlaidPaymentsResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, PlaidPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, PlaidPaymentsResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, PlaidPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { - let status = enums::AttemptStatus::from(item.response.status.clone()); + let status = AttemptStatus::from(item.response.status.clone()); Ok(Self { status, response: if is_payment_failure(status) { - Err(types::ErrorResponse { + Err(ErrorResponse { // populating status everywhere as plaid only sends back a status code: item.response.status.clone().to_string(), message: item.response.status.clone().to_string(), @@ -307,8 +312,8 @@ impl<F, T> network_error_message: None, }) } else { - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.payment_id.clone(), ), redirection_data: Box::new(None), @@ -330,21 +335,20 @@ pub struct PlaidLinkTokenResponse { link_token: String, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, PlaidLinkTokenResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, PlaidLinkTokenResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { - let session_token = Some(api::OpenBankingSessionToken { + let session_token = Some(OpenBankingSessionToken { open_banking_session_token: item.response.link_token, }); Ok(Self { - status: enums::AttemptStatus::AuthenticationPending, - response: Ok(types::PaymentsResponseData::PostProcessingResponse { session_token }), + status: AttemptStatus::AuthenticationPending, + response: Ok(PaymentsResponseData::PostProcessingResponse { session_token }), ..item.data }) } @@ -372,18 +376,18 @@ pub struct PlaidSyncResponse { request_id: String, } -impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidSyncResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, PlaidSyncResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, PlaidSyncResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, PlaidSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { - let status = enums::AttemptStatus::from(item.response.status.clone()); + let status = AttemptStatus::from(item.response.status.clone()); Ok(Self { status, response: if is_payment_failure(status) { - Err(types::ErrorResponse { + Err(ErrorResponse { // populating status everywhere as plaid only sends back a status code: item.response.status.clone().to_string(), message: item.response.status.clone().to_string(), @@ -396,8 +400,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidSyncResponse, T, types::Pay network_error_message: None, }) } else { - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.payment_id.clone(), ), redirection_data: Box::new(None), diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs index 72ef4d09a04..e0114269612 100644 --- a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs @@ -1314,7 +1314,7 @@ impl<F> } } -pub fn get_apple_pay_session<F, T>( +pub(crate) fn get_apple_pay_session<F, T>( instance_id: String, secrets: &SdkSecretInfo, apple_pay_init_result: TrustpayApplePayResponse, @@ -1366,7 +1366,7 @@ pub fn get_apple_pay_session<F, T>( }) } -pub fn get_google_pay_session<F, T>( +pub(crate) fn get_google_pay_session<F, T>( instance_id: String, secrets: &SdkSecretInfo, google_pay_init_result: TrustpayGooglePayResponse, diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 4a597eb6280..f8a274d1e1d 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -118,6 +118,7 @@ macro_rules! default_imp_for_authorize_session_token { default_imp_for_authorize_session_token!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -140,6 +141,7 @@ default_imp_for_authorize_session_token!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -150,6 +152,7 @@ default_imp_for_authorize_session_token!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -158,6 +161,7 @@ default_imp_for_authorize_session_token!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -174,6 +178,7 @@ default_imp_for_authorize_session_token!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -220,6 +225,7 @@ macro_rules! default_imp_for_calculate_tax { default_imp_for_calculate_tax!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -242,6 +248,7 @@ default_imp_for_calculate_tax!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -252,6 +259,7 @@ default_imp_for_calculate_tax!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -264,6 +272,7 @@ default_imp_for_calculate_tax!( connectors::Mollie, connectors::Moneris, connectors::Multisafepay, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, @@ -281,6 +290,7 @@ default_imp_for_calculate_tax!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, @@ -323,6 +333,7 @@ macro_rules! default_imp_for_session_update { default_imp_for_session_update!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -344,6 +355,7 @@ default_imp_for_session_update!( connectors::Datatrans, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -371,6 +383,7 @@ default_imp_for_session_update!( connectors::Mollie, connectors::Moneris, connectors::Multisafepay, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -387,11 +400,13 @@ default_imp_for_session_update!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::UnifiedAuthenticationService, connectors::Fiuu, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Worldline, connectors::Worldpay, @@ -426,6 +441,7 @@ macro_rules! default_imp_for_post_session_tokens { default_imp_for_post_session_tokens!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -447,6 +463,7 @@ default_imp_for_post_session_tokens!( connectors::Datatrans, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -474,6 +491,7 @@ default_imp_for_post_session_tokens!( connectors::Mollie, connectors::Moneris, connectors::Multisafepay, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -490,10 +508,12 @@ default_imp_for_post_session_tokens!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Fiuu, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Worldline, connectors::Worldpay, @@ -529,6 +549,7 @@ macro_rules! default_imp_for_update_metadata { default_imp_for_update_metadata!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -550,6 +571,7 @@ default_imp_for_update_metadata!( connectors::Datatrans, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -577,6 +599,7 @@ default_imp_for_update_metadata!( connectors::Mollie, connectors::Moneris, connectors::Multisafepay, + connectors::Netcetera, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -592,11 +615,13 @@ default_imp_for_update_metadata!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Payone, connectors::Fiuu, connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Worldline, connectors::Worldpay, @@ -635,6 +660,7 @@ macro_rules! default_imp_for_complete_authorize { default_imp_for_complete_authorize!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Amazonpay, connectors::Bamboraapac, connectors::Bankofamerica, @@ -649,6 +675,7 @@ default_imp_for_complete_authorize!( connectors::Cryptopay, connectors::Datatrans, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -658,6 +685,7 @@ default_imp_for_complete_authorize!( connectors::Getnet, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -669,6 +697,7 @@ default_imp_for_complete_authorize!( connectors::Mifinity, connectors::Moneris, connectors::Multisafepay, + connectors::Netcetera, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -680,6 +709,7 @@ default_imp_for_complete_authorize!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -719,6 +749,7 @@ macro_rules! default_imp_for_incremental_authorization { default_imp_for_incremental_authorization!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -740,6 +771,7 @@ default_imp_for_incremental_authorization!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -750,6 +782,7 @@ default_imp_for_incremental_authorization!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -758,6 +791,7 @@ default_imp_for_incremental_authorization!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -775,6 +809,7 @@ default_imp_for_incremental_authorization!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -822,6 +857,7 @@ macro_rules! default_imp_for_create_customer { default_imp_for_create_customer!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -844,6 +880,7 @@ default_imp_for_create_customer!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Fiserv, connectors::Fiservemea, @@ -852,6 +889,7 @@ default_imp_for_create_customer!( connectors::Getnet, connectors::Globalpay, connectors::Globepay, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -864,6 +902,7 @@ default_imp_for_create_customer!( connectors::Mollie, connectors::Moneris, connectors::Multisafepay, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -881,6 +920,7 @@ default_imp_for_create_customer!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, @@ -926,6 +966,7 @@ macro_rules! default_imp_for_connector_redirect_response { default_imp_for_connector_redirect_response!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Amazonpay, connectors::Billwerk, connectors::Bitpay, @@ -941,6 +982,7 @@ default_imp_for_connector_redirect_response!( connectors::Datatrans, connectors::Deutschebank, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -950,6 +992,7 @@ default_imp_for_connector_redirect_response!( connectors::Getnet, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -961,6 +1004,7 @@ default_imp_for_connector_redirect_response!( connectors::Mifinity, connectors::Moneris, connectors::Multisafepay, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, @@ -970,6 +1014,7 @@ default_imp_for_connector_redirect_response!( connectors::Payone, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, @@ -1009,6 +1054,7 @@ macro_rules! default_imp_for_pre_processing_steps{ default_imp_for_pre_processing_steps!( connectors::Aci, + connectors::Adyenplatform, connectors::Amazonpay, connectors::Authorizedotnet, connectors::Bambora, @@ -1029,6 +1075,7 @@ default_imp_for_pre_processing_steps!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1038,6 +1085,7 @@ default_imp_for_pre_processing_steps!( connectors::Getnet, connectors::Globalpay, connectors::Globepay, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1046,6 +1094,7 @@ default_imp_for_pre_processing_steps!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1058,6 +1107,7 @@ default_imp_for_pre_processing_steps!( connectors::Payone, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1102,6 +1152,7 @@ macro_rules! default_imp_for_post_processing_steps{ default_imp_for_post_processing_steps!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1124,6 +1175,7 @@ default_imp_for_post_processing_steps!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1134,6 +1186,7 @@ default_imp_for_post_processing_steps!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1142,6 +1195,7 @@ default_imp_for_post_processing_steps!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -1207,6 +1261,7 @@ macro_rules! default_imp_for_approve { default_imp_for_approve!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1229,6 +1284,7 @@ default_imp_for_approve!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1239,6 +1295,7 @@ default_imp_for_approve!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1247,6 +1304,7 @@ default_imp_for_approve!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1264,6 +1322,7 @@ default_imp_for_approve!( connectors::Payone, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1312,6 +1371,7 @@ macro_rules! default_imp_for_reject { default_imp_for_reject!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1334,6 +1394,7 @@ default_imp_for_reject!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1344,6 +1405,7 @@ default_imp_for_reject!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1352,6 +1414,7 @@ default_imp_for_reject!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -1369,6 +1432,7 @@ default_imp_for_reject!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1417,6 +1481,7 @@ macro_rules! default_imp_for_webhook_source_verification { default_imp_for_webhook_source_verification!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1440,6 +1505,7 @@ default_imp_for_webhook_source_verification!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Ebanx, connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, @@ -1449,6 +1515,7 @@ default_imp_for_webhook_source_verification!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1457,6 +1524,7 @@ default_imp_for_webhook_source_verification!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -1473,6 +1541,7 @@ default_imp_for_webhook_source_verification!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1521,6 +1590,7 @@ macro_rules! default_imp_for_accept_dispute { default_imp_for_accept_dispute!( connectors::Aci, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1542,6 +1612,7 @@ default_imp_for_accept_dispute!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1552,6 +1623,7 @@ default_imp_for_accept_dispute!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1560,6 +1632,7 @@ default_imp_for_accept_dispute!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -1577,6 +1650,7 @@ default_imp_for_accept_dispute!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1624,6 +1698,7 @@ macro_rules! default_imp_for_submit_evidence { default_imp_for_submit_evidence!( connectors::Aci, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1645,6 +1720,7 @@ default_imp_for_submit_evidence!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1655,6 +1731,7 @@ default_imp_for_submit_evidence!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1663,6 +1740,7 @@ default_imp_for_submit_evidence!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -1680,6 +1758,7 @@ default_imp_for_submit_evidence!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1727,6 +1806,7 @@ macro_rules! default_imp_for_defend_dispute { default_imp_for_defend_dispute!( connectors::Aci, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1748,6 +1828,7 @@ default_imp_for_defend_dispute!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1758,6 +1839,7 @@ default_imp_for_defend_dispute!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Iatapay, connectors::Inespay, @@ -1766,6 +1848,7 @@ default_imp_for_defend_dispute!( connectors::Juspaythreedsserver, connectors::Klarna, connectors::Helcim, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -1783,6 +1866,7 @@ default_imp_for_defend_dispute!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1839,6 +1923,7 @@ macro_rules! default_imp_for_file_upload { default_imp_for_file_upload!( connectors::Aci, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1860,6 +1945,7 @@ default_imp_for_file_upload!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1870,6 +1956,7 @@ default_imp_for_file_upload!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1878,6 +1965,7 @@ default_imp_for_file_upload!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -1895,6 +1983,7 @@ default_imp_for_file_upload!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1966,6 +2055,7 @@ default_imp_for_payouts!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1983,6 +2073,7 @@ default_imp_for_payouts!( connectors::Opayo, connectors::Opennode, connectors::Paybox, + connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, @@ -1992,6 +2083,7 @@ default_imp_for_payouts!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Rapyd, @@ -2036,6 +2128,7 @@ macro_rules! default_imp_for_payouts_create { #[cfg(feature = "payouts")] default_imp_for_payouts_create!( connectors::Aci, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2068,6 +2161,7 @@ default_imp_for_payouts_create!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2076,6 +2170,7 @@ default_imp_for_payouts_create!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, @@ -2091,6 +2186,7 @@ default_imp_for_payouts_create!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2141,6 +2237,7 @@ macro_rules! default_imp_for_payouts_retrieve { default_imp_for_payouts_retrieve!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2163,6 +2260,7 @@ default_imp_for_payouts_retrieve!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -2173,6 +2271,7 @@ default_imp_for_payouts_retrieve!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2181,6 +2280,7 @@ default_imp_for_payouts_retrieve!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, @@ -2196,6 +2296,7 @@ default_imp_for_payouts_retrieve!( connectors::Payu, connectors::Payone, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2245,6 +2346,7 @@ macro_rules! default_imp_for_payouts_eligibility { #[cfg(feature = "payouts")] default_imp_for_payouts_eligibility!( connectors::Aci, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2277,6 +2379,7 @@ default_imp_for_payouts_eligibility!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2285,6 +2388,7 @@ default_imp_for_payouts_eligibility!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, @@ -2301,6 +2405,7 @@ default_imp_for_payouts_eligibility!( connectors::Payone, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2381,6 +2486,7 @@ default_imp_for_payouts_fulfill!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2389,6 +2495,7 @@ default_imp_for_payouts_fulfill!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2403,6 +2510,7 @@ default_imp_for_payouts_fulfill!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2452,6 +2560,7 @@ macro_rules! default_imp_for_payouts_cancel { #[cfg(feature = "payouts")] default_imp_for_payouts_cancel!( connectors::Aci, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2484,6 +2593,7 @@ default_imp_for_payouts_cancel!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2492,6 +2602,7 @@ default_imp_for_payouts_cancel!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, @@ -2508,6 +2619,7 @@ default_imp_for_payouts_cancel!( connectors::Payone, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2558,6 +2670,7 @@ macro_rules! default_imp_for_payouts_quote { default_imp_for_payouts_quote!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2590,6 +2703,7 @@ default_imp_for_payouts_quote!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2598,6 +2712,7 @@ default_imp_for_payouts_quote!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, @@ -2614,6 +2729,7 @@ default_imp_for_payouts_quote!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2664,6 +2780,7 @@ macro_rules! default_imp_for_payouts_recipient { default_imp_for_payouts_recipient!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2696,6 +2813,7 @@ default_imp_for_payouts_recipient!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2704,6 +2822,7 @@ default_imp_for_payouts_recipient!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, @@ -2720,6 +2839,7 @@ default_imp_for_payouts_recipient!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2770,6 +2890,7 @@ macro_rules! default_imp_for_payouts_recipient_account { default_imp_for_payouts_recipient_account!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2792,6 +2913,7 @@ default_imp_for_payouts_recipient_account!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -2802,6 +2924,7 @@ default_imp_for_payouts_recipient_account!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2810,6 +2933,7 @@ default_imp_for_payouts_recipient_account!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, @@ -2826,6 +2950,7 @@ default_imp_for_payouts_recipient_account!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2876,6 +3001,7 @@ macro_rules! default_imp_for_frm_sale { default_imp_for_frm_sale!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2898,6 +3024,7 @@ default_imp_for_frm_sale!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -2908,6 +3035,7 @@ default_imp_for_frm_sale!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2916,6 +3044,7 @@ default_imp_for_frm_sale!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nomupay, connectors::Nmi, connectors::Noon, @@ -2933,6 +3062,7 @@ default_imp_for_frm_sale!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2982,6 +3112,7 @@ macro_rules! default_imp_for_frm_checkout { default_imp_for_frm_checkout!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -3004,6 +3135,7 @@ default_imp_for_frm_checkout!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -3014,6 +3146,7 @@ default_imp_for_frm_checkout!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -3022,6 +3155,7 @@ default_imp_for_frm_checkout!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -3039,6 +3173,7 @@ default_imp_for_frm_checkout!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -3088,6 +3223,7 @@ macro_rules! default_imp_for_frm_transaction { default_imp_for_frm_transaction!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -3110,6 +3246,7 @@ default_imp_for_frm_transaction!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -3120,6 +3257,7 @@ default_imp_for_frm_transaction!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -3128,6 +3266,7 @@ default_imp_for_frm_transaction!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -3145,6 +3284,7 @@ default_imp_for_frm_transaction!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -3194,6 +3334,7 @@ macro_rules! default_imp_for_frm_fulfillment { default_imp_for_frm_fulfillment!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -3216,6 +3357,7 @@ default_imp_for_frm_fulfillment!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -3226,6 +3368,7 @@ default_imp_for_frm_fulfillment!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -3234,6 +3377,7 @@ default_imp_for_frm_fulfillment!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -3251,6 +3395,7 @@ default_imp_for_frm_fulfillment!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -3300,6 +3445,7 @@ macro_rules! default_imp_for_frm_record_return { default_imp_for_frm_record_return!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -3322,6 +3468,7 @@ default_imp_for_frm_record_return!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -3332,6 +3479,7 @@ default_imp_for_frm_record_return!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -3340,6 +3488,7 @@ default_imp_for_frm_record_return!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -3357,6 +3506,7 @@ default_imp_for_frm_record_return!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -3403,6 +3553,7 @@ macro_rules! default_imp_for_revoking_mandates { default_imp_for_revoking_mandates!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -3423,6 +3574,7 @@ default_imp_for_revoking_mandates!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -3433,6 +3585,7 @@ default_imp_for_revoking_mandates!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -3441,6 +3594,7 @@ default_imp_for_revoking_mandates!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Novalnet, @@ -3457,6 +3611,7 @@ default_imp_for_revoking_mandates!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -3504,6 +3659,7 @@ macro_rules! default_imp_for_uas_pre_authentication { default_imp_for_uas_pre_authentication!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -3527,6 +3683,7 @@ default_imp_for_uas_pre_authentication!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -3537,6 +3694,7 @@ default_imp_for_uas_pre_authentication!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -3544,6 +3702,7 @@ default_imp_for_uas_pre_authentication!( connectors::Itaubank, connectors::Jpmorgan, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -3567,6 +3726,7 @@ default_imp_for_uas_pre_authentication!( connectors::Multisafepay, connectors::Paybox, connectors::Placetopay, + connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -3606,6 +3766,7 @@ macro_rules! default_imp_for_uas_post_authentication { default_imp_for_uas_post_authentication!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -3629,6 +3790,7 @@ default_imp_for_uas_post_authentication!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -3639,6 +3801,7 @@ default_imp_for_uas_post_authentication!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -3646,6 +3809,7 @@ default_imp_for_uas_post_authentication!( connectors::Itaubank, connectors::Jpmorgan, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -3663,6 +3827,7 @@ default_imp_for_uas_post_authentication!( connectors::Payu, connectors::Powertranz, connectors::Prophetpay, + connectors::Plaid, connectors::Mifinity, connectors::Mollie, connectors::Moneris, @@ -3709,6 +3874,7 @@ macro_rules! default_imp_for_uas_authentication_confirmation { default_imp_for_uas_authentication_confirmation!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -3732,6 +3898,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -3742,6 +3909,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -3749,6 +3917,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Itaubank, connectors::Jpmorgan, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -3772,6 +3941,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Paybox, connectors::Paypal, connectors::Placetopay, + connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -3804,6 +3974,7 @@ macro_rules! default_imp_for_connector_request_id { default_imp_for_connector_request_id!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Authorizedotnet, connectors::Amazonpay, @@ -3827,6 +3998,7 @@ default_imp_for_connector_request_id!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -3837,6 +4009,7 @@ default_imp_for_connector_request_id!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Iatapay, connectors::Inespay, @@ -3844,6 +4017,7 @@ default_imp_for_connector_request_id!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Novalnet, @@ -3866,6 +4040,7 @@ default_imp_for_connector_request_id!( connectors::Multisafepay, connectors::Paybox, connectors::Placetopay, + connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -3901,6 +4076,7 @@ macro_rules! default_imp_for_fraud_check { default_imp_for_fraud_check!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -3924,6 +4100,7 @@ default_imp_for_fraud_check!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -3934,6 +4111,7 @@ default_imp_for_fraud_check!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::Iatapay, @@ -3942,6 +4120,7 @@ default_imp_for_fraud_check!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Novalnet, @@ -3965,6 +4144,7 @@ default_imp_for_fraud_check!( connectors::Payme, connectors::Payone, connectors::Placetopay, + connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -4029,6 +4209,7 @@ macro_rules! default_imp_for_connector_authentication { default_imp_for_connector_authentication!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -4052,6 +4233,7 @@ default_imp_for_connector_authentication!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -4093,6 +4275,7 @@ default_imp_for_connector_authentication!( connectors::Payme, connectors::Paypal, connectors::Placetopay, + connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -4132,6 +4315,7 @@ macro_rules! default_imp_for_uas_authentication { default_imp_for_uas_authentication!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -4155,6 +4339,7 @@ default_imp_for_uas_authentication!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -4165,6 +4350,7 @@ default_imp_for_uas_authentication!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::Iatapay, @@ -4172,6 +4358,7 @@ default_imp_for_uas_authentication!( connectors::Itaubank, connectors::Jpmorgan, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Novalnet, @@ -4195,6 +4382,7 @@ default_imp_for_uas_authentication!( connectors::Payme, connectors::Payone, connectors::Placetopay, + connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -4227,6 +4415,7 @@ macro_rules! default_imp_for_revenue_recovery { default_imp_for_revenue_recovery! { connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -4250,6 +4439,7 @@ default_imp_for_revenue_recovery! { connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -4260,6 +4450,7 @@ default_imp_for_revenue_recovery! { connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -4268,6 +4459,7 @@ default_imp_for_revenue_recovery! { connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -4291,6 +4483,7 @@ default_imp_for_revenue_recovery! { connectors::Payme, connectors::Payone, connectors::Placetopay, + connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -4333,6 +4526,7 @@ macro_rules! default_imp_for_billing_connector_payment_sync { default_imp_for_billing_connector_payment_sync!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -4356,6 +4550,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -4366,6 +4561,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::Iatapay, @@ -4375,6 +4571,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Jpmorgan, connectors::Klarna, connectors::Nomupay, + connectors::Netcetera, connectors::Nmi, connectors::Noon, connectors::Novalnet, @@ -4397,6 +4594,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Payme, connectors::Payone, connectors::Placetopay, + connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -4438,6 +4636,7 @@ macro_rules! default_imp_for_revenue_recovery_record_back { default_imp_for_revenue_recovery_record_back!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -4460,6 +4659,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -4470,6 +4670,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::Iatapay, @@ -4478,6 +4679,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Netcetera, connectors::Nmi, connectors::Nomupay, connectors::Noon, @@ -4501,6 +4703,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Payme, connectors::Payone, connectors::Placetopay, + connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, @@ -4542,6 +4745,7 @@ macro_rules! default_imp_for_billing_connector_invoice_sync { default_imp_for_billing_connector_invoice_sync!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -4566,6 +4770,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Ebanx, connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, @@ -4575,6 +4780,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::Iatapay, @@ -4587,6 +4793,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Nmi, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nuvei, @@ -4606,6 +4813,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Payme, connectors::Payone, connectors::Placetopay, + connectors::Plaid, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 0c17f4942f2..c131cab0f1b 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -242,6 +242,7 @@ macro_rules! default_imp_for_new_connector_integration_payment { default_imp_for_new_connector_integration_payment!( connectors::Airwallex, connectors::Amazonpay, + connectors::Adyenplatform, connectors::Authorizedotnet, connectors::Bambora, connectors::Bamboraapac, @@ -263,6 +264,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -273,6 +275,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -284,6 +287,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -298,6 +302,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -346,6 +351,7 @@ macro_rules! default_imp_for_new_connector_integration_refund { default_imp_for_new_connector_integration_refund!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -369,6 +375,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -379,6 +386,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -390,6 +398,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -404,6 +413,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -447,6 +457,7 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token { default_imp_for_new_connector_integration_connector_access_token!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -470,6 +481,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -480,6 +492,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -491,6 +504,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -505,6 +519,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -554,6 +569,7 @@ macro_rules! default_imp_for_new_connector_integration_accept_dispute { default_imp_for_new_connector_integration_accept_dispute!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -576,6 +592,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -586,6 +603,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -597,6 +615,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -611,6 +630,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -659,6 +679,7 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence { default_imp_for_new_connector_integration_submit_evidence!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -681,6 +702,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -691,6 +713,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -702,6 +725,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -716,6 +740,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -764,6 +789,7 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute { default_imp_for_new_connector_integration_defend_dispute!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -787,6 +813,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -797,6 +824,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -808,6 +836,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -822,6 +851,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -880,6 +910,7 @@ macro_rules! default_imp_for_new_connector_integration_file_upload { default_imp_for_new_connector_integration_file_upload!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -903,6 +934,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -913,6 +945,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -924,13 +957,14 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, - connectors::Nmi, - connectors::Payone, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Nuvei, connectors::Opayo, connectors::Opennode, - connectors::Nuvei, + connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payme, @@ -938,6 +972,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -988,6 +1023,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create { default_imp_for_new_connector_integration_payouts_create!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1011,6 +1047,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1021,6 +1058,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1032,6 +1070,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, @@ -1046,6 +1085,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1096,6 +1136,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility { default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1119,6 +1160,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1129,6 +1171,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1140,6 +1183,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -1154,6 +1198,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1204,6 +1249,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill { default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1227,6 +1273,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1237,6 +1284,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1248,6 +1296,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -1262,6 +1311,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1312,6 +1362,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel { default_imp_for_new_connector_integration_payouts_cancel!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1335,6 +1386,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1345,6 +1397,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1356,6 +1409,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -1370,6 +1424,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1420,6 +1475,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote { default_imp_for_new_connector_integration_payouts_quote!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1443,6 +1499,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1453,6 +1510,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1464,6 +1522,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -1478,6 +1537,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1528,6 +1588,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient { default_imp_for_new_connector_integration_payouts_recipient!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1551,6 +1612,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1561,6 +1623,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1572,6 +1635,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -1586,6 +1650,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1636,6 +1701,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync { default_imp_for_new_connector_integration_payouts_sync!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1659,6 +1725,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1669,6 +1736,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1680,6 +1748,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -1694,6 +1763,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1744,6 +1814,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1767,6 +1838,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1777,6 +1849,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1788,6 +1861,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -1802,6 +1876,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1850,6 +1925,7 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1873,6 +1949,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1883,6 +1960,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -1894,6 +1972,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -1908,6 +1987,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -1958,6 +2038,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale { default_imp_for_new_connector_integration_frm_sale!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -1981,6 +2062,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -1991,6 +2073,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2002,6 +2085,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -2016,6 +2100,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2066,6 +2151,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout { default_imp_for_new_connector_integration_frm_checkout!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2089,6 +2175,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -2099,6 +2186,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2110,6 +2198,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -2124,6 +2213,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2174,6 +2264,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction { default_imp_for_new_connector_integration_frm_transaction!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2197,6 +2288,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -2207,6 +2299,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2218,6 +2311,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -2232,6 +2326,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2282,6 +2377,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment { default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2305,6 +2401,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -2315,6 +2412,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2326,6 +2424,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -2340,6 +2439,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2390,6 +2490,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return { default_imp_for_new_connector_integration_frm_record_return!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2413,6 +2514,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -2423,6 +2525,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2434,6 +2537,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -2448,6 +2552,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2495,6 +2600,7 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates { default_imp_for_new_connector_integration_revoking_mandates!( connectors::Aci, connectors::Adyen, + connectors::Adyenplatform, connectors::Airwallex, connectors::Amazonpay, connectors::Authorizedotnet, @@ -2518,6 +2624,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -2528,6 +2635,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Globalpay, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Hipay, connectors::Helcim, connectors::Iatapay, @@ -2539,6 +2647,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -2552,6 +2661,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -2608,6 +2718,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -2617,12 +2728,14 @@ default_imp_for_new_connector_integration_frm!( connectors::Globepay, connectors::Hipay, connectors::Gocardless, + connectors::Gpayments, connectors::Helcim, connectors::Inespay, connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Nomupay, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -2631,6 +2744,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Payeezy, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mollie, @@ -2715,6 +2829,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, + connectors::Ebanx, connectors::Elavon, connectors::Facilitapay, connectors::Fiserv, @@ -2723,6 +2838,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Forte, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::Inespay, @@ -2730,12 +2846,14 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Juspaythreedsserver, connectors::Nomupay, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Paybox, connectors::Payeezy, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mollie, @@ -2812,6 +2930,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Ebanx, connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, @@ -2819,6 +2938,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Forte, connectors::Globepay, connectors::Gocardless, + connectors::Gpayments, connectors::Helcim, connectors::Hipay, connectors::Inespay, @@ -2826,6 +2946,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Juspaythreedsserver, connectors::Nomupay, connectors::Novalnet, + connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, connectors::Nmi, @@ -2834,6 +2955,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Payeezy, connectors::Payu, connectors::Placetopay, + connectors::Plaid, connectors::Powertranz, connectors::Prophetpay, connectors::Mollie, diff --git a/crates/hyperswitch_connectors/src/types.rs b/crates/hyperswitch_connectors/src/types.rs index 4a36f22cb99..79c032a8dae 100644 --- a/crates/hyperswitch_connectors/src/types.rs +++ b/crates/hyperswitch_connectors/src/types.rs @@ -1,26 +1,39 @@ +#[cfg(feature = "v2")] +use hyperswitch_domain_models::router_data_v2::RouterDataV2; #[cfg(feature = "payouts")] use hyperswitch_domain_models::types::{PayoutsData, PayoutsResponseData}; use hyperswitch_domain_models::{ router_data::{AccessToken, RouterData}, - router_data_v2::RouterDataV2, router_flow_types::{ - Accept, AccessTokenAuth, Authorize, Capture, Checkout, Defend, Evidence, Fulfillment, - PSync, PreProcessing, Session, Transaction, Upload, Void, + authentication::{ + Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, + }, + Accept, AccessTokenAuth, Authorize, Capture, Defend, Evidence, PSync, PostProcessing, + PreProcessing, Session, Upload, Void, }, router_request_types::{ - fraud_check::{ - FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckTransactionData, + authentication::{ + ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, + PreAuthNRequestData, }, AcceptDisputeRequestData, AccessTokenRequestData, DefendDisputeRequestData, - PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, - PaymentsSessionData, PaymentsSyncData, RefundsData, SubmitEvidenceRequestData, - UploadFileRequestData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPostProcessingData, + PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, + SubmitEvidenceRequestData, UploadFileRequestData, }, router_response_types::{ - fraud_check::FraudCheckResponseData, AcceptDisputeResponse, DefendDisputeResponse, + AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, PaymentsResponseData, RefundsResponseData, SubmitEvidenceResponse, UploadFileResponse, }, }; +#[cfg(feature = "frm")] +use hyperswitch_domain_models::{ + router_flow_types::{Checkout, Fulfillment, Transaction}, + router_request_types::fraud_check::{ + FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckTransactionData, + }, + router_response_types::fraud_check::FraudCheckResponseData, +}; use hyperswitch_interfaces::api::ConnectorIntegration; pub(crate) type PaymentsSyncResponseRouterData<R> = @@ -51,30 +64,68 @@ pub(crate) type DefendDisputeRouterData = RouterData<Defend, DefendDisputeRequestData, DefendDisputeResponse>; #[cfg(feature = "payouts")] -pub type PayoutsResponseRouterData<F, R> = +pub(crate) type PayoutsResponseRouterData<F, R> = ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>; // TODO: Remove `ResponseRouterData` from router crate after all the related type aliases are moved to this crate. -pub struct ResponseRouterData<Flow, R, Request, Response> { - pub response: R, - pub data: RouterData<Flow, Request, Response>, - pub http_code: u16, +pub(crate) struct ResponseRouterData<Flow, R, Request, Response> { + pub(crate) response: R, + pub(crate) data: RouterData<Flow, Request, Response>, + pub(crate) http_code: u16, } -pub type FrmFulfillmentRouterData = +#[cfg(feature = "frm")] +pub(crate) type FrmFulfillmentRouterData = RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>; -pub type FrmCheckoutType = +#[cfg(feature = "frm")] +pub(crate) type FrmCheckoutType = dyn ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData>; -pub type FrmTransactionType = +#[cfg(feature = "frm")] +pub(crate) type FrmTransactionType = dyn ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData>; -pub type FrmTransactionRouterData = +#[cfg(feature = "frm")] +pub(crate) type FrmTransactionRouterData = RouterData<Transaction, FraudCheckTransactionData, FraudCheckResponseData>; -pub type FrmFulfillmentType = +#[cfg(feature = "frm")] +pub(crate) type FrmFulfillmentType = dyn ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>; -pub type FrmCheckoutRouterData = +#[cfg(feature = "frm")] +pub(crate) type FrmCheckoutRouterData = RouterData<Checkout, FraudCheckCheckoutData, FraudCheckResponseData>; - -pub struct ResponseRouterDataV2<Flow, R, ResourceCommonData, Request, Response> { +#[cfg(feature = "v2")] +pub(crate) struct ResponseRouterDataV2<Flow, R, ResourceCommonData, Request, Response> { pub response: R, pub data: RouterDataV2<Flow, ResourceCommonData, Request, Response>, pub http_code: u16, } + +pub(crate) type PreAuthNRouterData = + RouterData<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData>; +pub(crate) type PreAuthNVersionCallRouterData = + RouterData<PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData>; +pub(crate) type ConnectorAuthenticationRouterData = + RouterData<Authentication, ConnectorAuthenticationRequestData, AuthenticationResponseData>; +pub(crate) type ConnectorPostAuthenticationRouterData = RouterData< + PostAuthentication, + ConnectorPostAuthenticationRequestData, + AuthenticationResponseData, +>; +pub(crate) type ConnectorAuthenticationType = dyn ConnectorIntegration< + Authentication, + ConnectorAuthenticationRequestData, + AuthenticationResponseData, +>; +pub(crate) type ConnectorPostAuthenticationType = dyn ConnectorIntegration< + PostAuthentication, + ConnectorPostAuthenticationRequestData, + AuthenticationResponseData, +>; +pub(crate) type ConnectorPreAuthenticationType = + dyn ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData>; +pub(crate) type ConnectorPreAuthenticationVersionCallType = dyn ConnectorIntegration< + PreAuthenticationVersionCall, + PreAuthNRequestData, + AuthenticationResponseData, +>; + +pub(crate) type PaymentsPostProcessingRouterData = + RouterData<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index a3ccc73c183..216b096b7a7 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -6220,3 +6220,75 @@ where _ => Ok(None), } } +#[cfg(feature = "payouts")] +pub trait CustomerDetails { + fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError>; + fn get_customer_name( + &self, + ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>; + fn get_customer_email(&self) -> Result<Email, errors::ConnectorError>; + fn get_customer_phone( + &self, + ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>; + fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError>; +} + +#[cfg(feature = "payouts")] +impl CustomerDetails for hyperswitch_domain_models::router_request_types::CustomerDetails { + fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError> { + self.customer_id + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "customer_id", + }) + } + + fn get_customer_name( + &self, + ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> { + self.name + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "customer_name", + }) + } + + fn get_customer_email(&self) -> Result<Email, errors::ConnectorError> { + self.email + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "customer_email", + }) + } + + fn get_customer_phone( + &self, + ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> { + self.phone + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "customer_phone", + }) + } + + fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError> { + self.phone_country_code + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "customer_phone_country_code", + }) + } +} + +pub fn get_card_details( + payment_method_data: PaymentMethodData, + connector_name: &'static str, +) -> Result<Card, errors::ConnectorError> { + match payment_method_data { + PaymentMethodData::Card(details) => Ok(details), + _ => Err(errors::ConnectorError::NotSupported { + message: SELECTED_PAYMENT_METHOD.to_string(), + connector: connector_name, + })?, + } +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 46f63abf501..e80b9672f23 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -115,7 +115,6 @@ tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] } totp-rs = { version = "5.5.1", features = ["gen_secret", "otpauth"] } tracing-futures = { version = "0.2.5", features = ["tokio"] } unicode-segmentation = "1.11.0" -unidecode = "0.3.0" url = { version = "2.5.0", features = ["serde"] } urlencoding = "2.1.3" utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order", "time"] } diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index e78c64d6fe9..e5a91afc78b 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -1,10 +1,5 @@ -pub mod adyenplatform; #[cfg(feature = "dummy_connector")] pub mod dummyconnector; -pub mod ebanx; -pub mod gpayments; -pub mod netcetera; -pub mod plaid; pub mod signifyd; pub mod stripe; pub mod threedsecureio; @@ -13,33 +8,35 @@ pub mod wellsfargopayout; pub mod wise; pub use hyperswitch_connectors::connectors::{ - aci, aci::Aci, adyen, adyen::Adyen, airwallex, airwallex::Airwallex, amazonpay, - amazonpay::Amazonpay, authorizedotnet, authorizedotnet::Authorizedotnet, bambora, - bambora::Bambora, bamboraapac, bamboraapac::Bamboraapac, bankofamerica, - bankofamerica::Bankofamerica, billwerk, billwerk::Billwerk, bitpay, bitpay::Bitpay, bluesnap, - bluesnap::Bluesnap, boku, boku::Boku, braintree, braintree::Braintree, cashtocode, - cashtocode::Cashtocode, chargebee::Chargebee, checkout, checkout::Checkout, coinbase, - coinbase::Coinbase, coingate, coingate::Coingate, cryptopay, cryptopay::Cryptopay, - ctp_mastercard, ctp_mastercard::CtpMastercard, cybersource, cybersource::Cybersource, - datatrans, datatrans::Datatrans, deutschebank, deutschebank::Deutschebank, digitalvirgo, - digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, elavon, elavon::Elavon, facilitapay, - facilitapay::Facilitapay, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, - fiuu::Fiuu, forte, forte::Forte, getnet, getnet::Getnet, globalpay, globalpay::Globalpay, - globepay, globepay::Globepay, gocardless, gocardless::Gocardless, helcim, helcim::Helcim, - hipay, hipay::Hipay, iatapay, iatapay::Iatapay, inespay, inespay::Inespay, itaubank, + aci, aci::Aci, adyen, adyen::Adyen, adyenplatform, adyenplatform::Adyenplatform, airwallex, + airwallex::Airwallex, amazonpay, amazonpay::Amazonpay, authorizedotnet, + authorizedotnet::Authorizedotnet, bambora, bambora::Bambora, bamboraapac, + bamboraapac::Bamboraapac, bankofamerica, bankofamerica::Bankofamerica, billwerk, + billwerk::Billwerk, bitpay, bitpay::Bitpay, bluesnap, bluesnap::Bluesnap, boku, boku::Boku, + braintree, braintree::Braintree, cashtocode, cashtocode::Cashtocode, chargebee, + chargebee::Chargebee, checkout, checkout::Checkout, coinbase, coinbase::Coinbase, coingate, + coingate::Coingate, cryptopay, cryptopay::Cryptopay, ctp_mastercard, + ctp_mastercard::CtpMastercard, cybersource, cybersource::Cybersource, datatrans, + datatrans::Datatrans, deutschebank, deutschebank::Deutschebank, digitalvirgo, + digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, ebanx, ebanx::Ebanx, elavon, + elavon::Elavon, facilitapay, facilitapay::Facilitapay, fiserv, fiserv::Fiserv, fiservemea, + fiservemea::Fiservemea, fiuu, fiuu::Fiuu, forte, forte::Forte, getnet, getnet::Getnet, + globalpay, globalpay::Globalpay, globepay, globepay::Globepay, gocardless, + gocardless::Gocardless, gpayments, gpayments::Gpayments, helcim, helcim::Helcim, hipay, + hipay::Hipay, iatapay, iatapay::Iatapay, inespay, inespay::Inespay, itaubank, itaubank::Itaubank, jpmorgan, jpmorgan::Jpmorgan, juspaythreedsserver, juspaythreedsserver::Juspaythreedsserver, klarna, klarna::Klarna, mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris, moneris::Moneris, multisafepay, multisafepay::Multisafepay, - nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nmi, nmi::Nmi, nomupay, - nomupay::Nomupay, noon, noon::Noon, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, - opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, - payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, paystack, - paystack::Paystack, payu, payu::Payu, placetopay, placetopay::Placetopay, powertranz, - powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, - razorpay::Razorpay, recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, - shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, stripebilling, - stripebilling::Stripebilling, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, trustpay, - trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service, + netcetera, netcetera::Netcetera, nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, + nmi, nmi::Nmi, nomupay, nomupay::Nomupay, noon, noon::Noon, novalnet, novalnet::Novalnet, + nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, + payeezy, payeezy::Payeezy, payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, + paystack, paystack::Paystack, payu, payu::Payu, placetopay, placetopay::Placetopay, plaid, + plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, + rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, recurly::Recurly, redsys, redsys::Redsys, + riskified, riskified::Riskified, shift4, shift4::Shift4, square, square::Square, stax, + stax::Stax, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, thunes, + thunes::Thunes, trustpay, trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, @@ -48,7 +45,6 @@ pub use hyperswitch_connectors::connectors::{ #[cfg(feature = "dummy_connector")] pub use self::dummyconnector::DummyConnector; pub use self::{ - adyenplatform::Adyenplatform, ebanx::Ebanx, gpayments::Gpayments, netcetera::Netcetera, - plaid::Plaid, signifyd::Signifyd, stripe::Stripe, threedsecureio::Threedsecureio, + signifyd::Signifyd, stripe::Stripe, threedsecureio::Threedsecureio, wellsfargopayout::Wellsfargopayout, wise::Wise, }; diff --git a/crates/router/src/connector/ebanx.rs b/crates/router/src/connector/ebanx.rs deleted file mode 100644 index 50e336daf21..00000000000 --- a/crates/router/src/connector/ebanx.rs +++ /dev/null @@ -1,473 +0,0 @@ -pub mod transformers; - -#[cfg(feature = "payouts")] -use common_utils::request::RequestContent; -#[cfg(feature = "payouts")] -use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}; -use error_stack::{report, ResultExt}; -#[cfg(feature = "payouts")] -use router_env::{instrument, tracing}; -use transformers as ebanx; - -#[cfg(feature = "payouts")] -use crate::connector::utils::convert_amount; -use crate::{ - configs::settings, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - services::{ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - }, - utils::BytesExt, -}; -#[cfg(feature = "payouts")] -use crate::{ - headers, - services::{self, request}, -}; -#[derive(Clone)] -pub struct Ebanx { - #[cfg(feature = "payouts")] - amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), -} - -impl Ebanx { - pub fn new() -> &'static Self { - &Self { - #[cfg(feature = "payouts")] - amount_converter: &FloatMajorUnitForConnector, - } - } -} - -impl api::Payment for Ebanx {} -impl api::PaymentSession for Ebanx {} -impl api::ConnectorAccessToken for Ebanx {} -impl api::MandateSetup for Ebanx {} -impl api::PaymentAuthorize for Ebanx {} -impl api::PaymentSync for Ebanx {} -impl api::PaymentCapture for Ebanx {} -impl api::PaymentVoid for Ebanx {} -impl api::Refund for Ebanx {} -impl api::RefundExecute for Ebanx {} -impl api::RefundSync for Ebanx {} -impl api::PaymentToken for Ebanx {} - -impl api::Payouts for Ebanx {} -#[cfg(feature = "payouts")] -impl api::PayoutCancel for Ebanx {} -#[cfg(feature = "payouts")] -impl api::PayoutCreate for Ebanx {} -#[cfg(feature = "payouts")] -impl api::PayoutEligibility for Ebanx {} -#[cfg(feature = "payouts")] -impl api::PayoutQuote for Ebanx {} -#[cfg(feature = "payouts")] -impl api::PayoutRecipient for Ebanx {} -#[cfg(feature = "payouts")] -impl api::PayoutFulfill for Ebanx {} - -impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Ebanx -where - Self: ConnectorIntegration<Flow, Request, Response>, -{ - #[cfg(feature = "payouts")] - fn build_headers( - &self, - _req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let header = vec![( - headers::CONTENT_TYPE.to_string(), - self.common_get_content_type().to_string().into(), - )]; - Ok(header) - } -} - -impl ConnectorCommon for Ebanx { - fn id(&self) -> &'static str { - "ebanx" - } - - fn get_currency_unit(&self) -> api::CurrencyUnit { - api::CurrencyUnit::Base - } - - fn common_get_content_type(&self) -> &'static str { - "application/json" - } - - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { - connectors.ebanx.base_url.as_ref() - } - - fn build_error_response( - &self, - res: types::Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: ebanx::EbanxErrorResponse = - res.response - .parse_struct("EbanxErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response.status_code, - message: response.code, - reason: response.message, - attempt_status: None, - connector_transaction_id: None, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - }) - } -} - -#[cfg(feature = "payouts")] -impl ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData> for Ebanx { - fn get_url( - &self, - _req: &types::PayoutsRouterData<api::PoCreate>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}ws/payout/create", connectors.ebanx.base_url)) - } - - fn get_headers( - &self, - req: &types::PayoutsRouterData<api::PoCreate>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_request_body( - &self, - req: &types::PayoutsRouterData<api::PoCreate>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = convert_amount( - self.amount_converter, - req.request.minor_amount, - req.request.source_currency, - )?; - let connector_router_data = ebanx::EbanxRouterData::from((amount, req)); - let connector_req = ebanx::EbanxPayoutCreateRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) - } - - fn build_request( - &self, - req: &types::PayoutsRouterData<api::PoCreate>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutCreateType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(types::PayoutCreateType::get_headers(self, req, connectors)?) - .set_body(types::PayoutCreateType::get_request_body( - self, req, connectors, - )?) - .build(); - - Ok(Some(request)) - } - - fn handle_response( - &self, - data: &types::PayoutsRouterData<api::PoCreate>, - event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> { - let response: ebanx::EbanxPayoutResponse = res - .response - .parse_struct("EbanxPayoutResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: types::Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -#[cfg(feature = "payouts")] -impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> - for Ebanx -{ - fn get_url( - &self, - _req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}ws/payout/commit", connectors.ebanx.base_url,)) - } - - fn get_headers( - &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_request_body( - &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = convert_amount( - self.amount_converter, - req.request.minor_amount, - req.request.source_currency, - )?; - let connector_router_data = ebanx::EbanxRouterData::from((amount, req)); - let connector_req = ebanx::EbanxPayoutFulfillRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) - } - - fn build_request( - &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) - .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)) - } - - #[instrument(skip_all)] - fn handle_response( - &self, - data: &types::PayoutsRouterData<api::PoFulfill>, - event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { - let response: ebanx::EbanxFulfillResponse = res - .response - .parse_struct("EbanxFulfillResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: types::Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -#[cfg(feature = "payouts")] -impl ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData> for Ebanx { - fn get_url( - &self, - _req: &types::PayoutsRouterData<api::PoCancel>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}ws/payout/cancel", connectors.ebanx.base_url,)) - } - - fn get_headers( - &self, - req: &types::PayoutsRouterData<api::PoCancel>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, _connectors) - } - - fn get_request_body( - &self, - req: &types::PayoutsRouterData<api::PoCancel>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = ebanx::EbanxPayoutCancelRequest::try_from(req)?; - Ok(RequestContent::Json(Box::new(connector_req))) - } - - fn build_request( - &self, - req: &types::PayoutsRouterData<api::PoCancel>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Put) - .url(&types::PayoutCancelType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(types::PayoutCancelType::get_headers(self, req, connectors)?) - .set_body(types::PayoutCancelType::get_request_body( - self, req, connectors, - )?) - .build(); - - Ok(Some(request)) - } - - #[instrument(skip_all)] - fn handle_response( - &self, - data: &types::PayoutsRouterData<api::PoCancel>, - event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> { - let response: ebanx::EbanxCancelResponse = res - .response - .parse_struct("EbanxCancelResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: types::Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -#[cfg(feature = "payouts")] -impl ConnectorIntegration<api::PoQuote, types::PayoutsData, types::PayoutsResponseData> for Ebanx {} - -#[cfg(feature = "payouts")] -impl ConnectorIntegration<api::PoRecipient, types::PayoutsData, types::PayoutsResponseData> - for Ebanx -{ -} - -#[cfg(feature = "payouts")] -impl ConnectorIntegration<api::PoEligibility, types::PayoutsData, types::PayoutsResponseData> - for Ebanx -{ -} - -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Ebanx -{ - // Not Implemented (R) -} - -impl ConnectorValidation for Ebanx { - //TODO: implement functions when support enabled -} - -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Ebanx -{ - //TODO: implement sessions flow -} - -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Ebanx -{ -} - -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Ebanx -{ -} - -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Ebanx -{ -} - -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Ebanx -{ -} - -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Ebanx -{ -} - -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Ebanx -{ -} - -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Ebanx {} - -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Ebanx {} - -impl api::IncomingWebhook for Ebanx { - fn get_webhook_object_reference_id( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) - } - - fn get_webhook_event_type( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) - } - - fn get_webhook_resource_object( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) - } -} - -impl ConnectorSpecifications for Ebanx {} diff --git a/crates/router/src/connector/gpayments.rs b/crates/router/src/connector/gpayments.rs deleted file mode 100644 index 26c1fb5ee28..00000000000 --- a/crates/router/src/connector/gpayments.rs +++ /dev/null @@ -1,620 +0,0 @@ -pub mod gpayments_types; -pub mod transformers; - -use common_utils::{ - request::RequestContent, - types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, -}; -use error_stack::{report, ResultExt}; -use transformers as gpayments; - -use crate::{ - configs::settings, - connector::{gpayments::gpayments_types::GpaymentsConnectorMetaData, utils::to_connector_meta}, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, services, - services::{request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, - }, - utils::BytesExt, -}; - -#[derive(Clone)] -pub struct Gpayments { - _amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), -} - -impl Gpayments { - pub fn new() -> &'static Self { - &Self { - _amount_converter: &MinorUnitForConnector, - } - } -} - -impl api::Payment for Gpayments {} -impl api::PaymentSession for Gpayments {} -impl api::ConnectorAccessToken for Gpayments {} -impl api::MandateSetup for Gpayments {} -impl api::PaymentAuthorize for Gpayments {} -impl api::PaymentSync for Gpayments {} -impl api::PaymentCapture for Gpayments {} -impl api::PaymentVoid for Gpayments {} -impl api::Refund for Gpayments {} -impl api::RefundExecute for Gpayments {} -impl api::RefundSync for Gpayments {} -impl api::PaymentToken for Gpayments {} - -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Gpayments -{ - // Not Implemented (R) -} - -impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Gpayments -where - Self: ConnectorIntegration<Flow, Request, Response>, -{ - fn build_headers( - &self, - _req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let header = vec![( - headers::CONTENT_TYPE.to_string(), - self.get_content_type().to_string().into(), - )]; - Ok(header) - } -} - -impl ConnectorCommon for Gpayments { - fn id(&self) -> &'static str { - "gpayments" - } - - fn get_currency_unit(&self) -> api::CurrencyUnit { - api::CurrencyUnit::Minor - // 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 settings::Connectors) -> &'a str { - connectors.gpayments.base_url.as_ref() - } - - fn get_auth_header( - &self, - _auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - Ok(vec![]) - } - - fn build_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: gpayments_types::TDS2ApiError = res - .response - .parse_struct("gpayments_types TDS2ApiError") - .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.error_code, - message: response.error_description, - reason: response.error_detail, - attempt_status: None, - connector_transaction_id: None, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - }) - } -} - -impl ConnectorValidation for Gpayments { - //TODO: implement functions when support enabled -} - -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Gpayments -{ -} - -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Gpayments -{ -} - -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Gpayments -{ -} - -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Gpayments -{ -} - -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Gpayments -{ -} - -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Gpayments -{ -} - -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Gpayments -{ -} - -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Gpayments -{ -} - -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Gpayments -{ -} - -#[async_trait::async_trait] -impl api::IncomingWebhook for Gpayments { - fn get_webhook_object_reference_id( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) - } - - fn get_webhook_event_type( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) - } - - fn get_webhook_resource_object( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) - } -} - -impl api::ExternalAuthentication for Gpayments {} -impl api::ConnectorAuthentication for Gpayments {} -impl api::ConnectorPreAuthentication for Gpayments {} -impl api::ConnectorPreAuthenticationVersionCall for Gpayments {} -impl api::ConnectorPostAuthentication for Gpayments {} - -fn build_endpoint( - base_url: &str, - connector_metadata: &Option<common_utils::pii::SecretSerdeValue>, -) -> CustomResult<String, errors::ConnectorError> { - let metadata = gpayments::GpaymentsMetaData::try_from(connector_metadata)?; - let endpoint_prefix = metadata.endpoint_prefix; - Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix)) -} - -impl - ConnectorIntegration< - api::Authentication, - types::authentication::ConnectorAuthenticationRequestData, - types::authentication::AuthenticationResponseData, - > for Gpayments -{ - fn get_headers( - &self, - req: &types::authentication::ConnectorAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - req: &types::authentication::ConnectorAuthenticationRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - let connector_metadata: GpaymentsConnectorMetaData = to_connector_meta( - req.request - .pre_authentication_data - .connector_metadata - .clone(), - )?; - Ok(connector_metadata.authentication_url) - } - - fn get_request_body( - &self, - req: &types::authentication::ConnectorAuthenticationRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req)); - let req_obj = - gpayments_types::GpaymentsAuthenticationRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(req_obj))) - } - fn build_request( - &self, - req: &types::authentication::ConnectorAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url( - &types::authentication::ConnectorAuthenticationType::get_url( - self, req, connectors, - )?, - ) - .attach_default_headers() - .headers( - types::authentication::ConnectorAuthenticationType::get_headers( - self, req, connectors, - )?, - ) - .set_body( - types::authentication::ConnectorAuthenticationType::get_request_body( - self, req, connectors, - )?, - ) - .add_certificate(Some(gpayments_auth_type.certificate)) - .add_certificate_key(Some(gpayments_auth_type.private_key)) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::authentication::ConnectorAuthenticationRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult< - types::authentication::ConnectorAuthenticationRouterData, - errors::ConnectorError, - > { - let response: gpayments_types::GpaymentsAuthenticationSuccessResponse = res - .response - .parse_struct("gpayments GpaymentsAuthenticationResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} -impl - ConnectorIntegration< - api::PostAuthentication, - types::authentication::ConnectorPostAuthenticationRequestData, - types::authentication::AuthenticationResponseData, - > for Gpayments -{ - fn get_headers( - &self, - req: &types::authentication::ConnectorPostAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - req: &types::authentication::ConnectorPostAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; - Ok(format!( - "{}/api/v2/auth/brw/result?threeDSServerTransID={}", - base_url, req.request.threeds_server_transaction_id, - )) - } - - fn build_request( - &self, - req: &types::authentication::ConnectorPostAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url( - &types::authentication::ConnectorPostAuthenticationType::get_url( - self, req, connectors, - )?, - ) - .attach_default_headers() - .headers( - types::authentication::ConnectorPostAuthenticationType::get_headers( - self, req, connectors, - )?, - ) - .add_certificate(Some(gpayments_auth_type.certificate)) - .add_certificate_key(Some(gpayments_auth_type.private_key)) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::authentication::ConnectorPostAuthenticationRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult< - types::authentication::ConnectorPostAuthenticationRouterData, - errors::ConnectorError, - > { - let response: gpayments_types::GpaymentsPostAuthenticationResponse = res - .response - .parse_struct("gpayments PaymentsSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - Ok( - types::authentication::ConnectorPostAuthenticationRouterData { - response: Ok( - types::authentication::AuthenticationResponseData::PostAuthNResponse { - trans_status: response.trans_status.into(), - authentication_value: response.authentication_value, - eci: response.eci, - }, - ), - ..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) - } -} - -impl - ConnectorIntegration< - api::PreAuthentication, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, - > for Gpayments -{ - fn get_headers( - &self, - req: &types::authentication::PreAuthNRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - req: &types::authentication::PreAuthNRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; - Ok(format!("{}/api/v2/auth/brw/init?mode=custom", base_url,)) - } - - fn get_request_body( - &self, - req: &types::authentication::PreAuthNRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req)); - let req_obj = - gpayments_types::GpaymentsPreAuthenticationRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(req_obj))) - } - - fn build_request( - &self, - req: &types::authentication::PreAuthNRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url( - &types::authentication::ConnectorPreAuthenticationType::get_url( - self, req, connectors, - )?, - ) - .attach_default_headers() - .headers( - types::authentication::ConnectorPreAuthenticationType::get_headers( - self, req, connectors, - )?, - ) - .set_body( - types::authentication::ConnectorPreAuthenticationType::get_request_body( - self, req, connectors, - )?, - ) - .add_certificate(Some(gpayments_auth_type.certificate)) - .add_certificate_key(Some(gpayments_auth_type.private_key)) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::authentication::PreAuthNRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::authentication::PreAuthNRouterData, errors::ConnectorError> { - let response: gpayments_types::GpaymentsPreAuthenticationResponse = res - .response - .parse_struct("gpayments GpaymentsPreAuthenticationResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} -impl - ConnectorIntegration< - api::PreAuthenticationVersionCall, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, - > for Gpayments -{ - fn get_headers( - &self, - req: &types::authentication::PreAuthNVersionCallRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - req: &types::authentication::PreAuthNVersionCallRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; - Ok(format!("{}/api/v2/auth/enrol", base_url,)) - } - - fn get_request_body( - &self, - req: &types::authentication::PreAuthNVersionCallRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req)); - let req_obj = - gpayments_types::GpaymentsPreAuthVersionCallRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(req_obj))) - } - - fn build_request( - &self, - req: &types::authentication::PreAuthNVersionCallRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url( - &types::authentication::ConnectorPreAuthenticationVersionCallType::get_url( - self, req, connectors, - )?, - ) - .attach_default_headers() - .headers( - types::authentication::ConnectorPreAuthenticationVersionCallType::get_headers( - self, req, connectors, - )?, - ) - .set_body( - types::authentication::ConnectorPreAuthenticationVersionCallType::get_request_body( - self, req, connectors, - )?, - ) - .add_certificate(Some(gpayments_auth_type.certificate)) - .add_certificate_key(Some(gpayments_auth_type.private_key)) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::authentication::PreAuthNVersionCallRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::authentication::PreAuthNVersionCallRouterData, errors::ConnectorError> - { - let response: gpayments_types::GpaymentsPreAuthVersionCallResponse = res - .response - .parse_struct("gpayments GpaymentsPreAuthVersionCallResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl ConnectorSpecifications for Gpayments {} diff --git a/crates/router/src/connector/netcetera.rs b/crates/router/src/connector/netcetera.rs deleted file mode 100644 index 058d737029e..00000000000 --- a/crates/router/src/connector/netcetera.rs +++ /dev/null @@ -1,469 +0,0 @@ -pub mod netcetera_types; -pub mod transformers; - -use std::fmt::Debug; - -use common_utils::{ext_traits::ByteSliceExt, request::RequestContent}; -use error_stack::ResultExt; -use hyperswitch_interfaces::authentication::ExternalAuthenticationPayload; -use transformers as netcetera; - -use crate::{ - configs::settings, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, - }, - utils::BytesExt, -}; - -#[derive(Debug, Clone)] -pub struct Netcetera; - -impl api::Payment for Netcetera {} -impl api::PaymentSession for Netcetera {} -impl api::ConnectorAccessToken for Netcetera {} -impl api::MandateSetup for Netcetera {} -impl api::PaymentAuthorize for Netcetera {} -impl api::PaymentSync for Netcetera {} -impl api::PaymentCapture for Netcetera {} -impl api::PaymentVoid for Netcetera {} -impl api::Refund for Netcetera {} -impl api::RefundExecute for Netcetera {} -impl api::RefundSync for Netcetera {} -impl api::PaymentToken for Netcetera {} - -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Netcetera -{ - // Not Implemented (R) -} - -impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Netcetera -where - Self: ConnectorIntegration<Flow, Request, Response>, -{ - fn build_headers( - &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - self.get_content_type().to_string().into(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) - } -} - -impl ConnectorCommon for Netcetera { - fn id(&self) -> &'static str { - "netcetera" - } - - fn get_currency_unit(&self) -> api::CurrencyUnit { - api::CurrencyUnit::Minor - } - - fn common_get_content_type(&self) -> &'static str { - "application/json" - } - - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { - connectors.netcetera.base_url.as_ref() - } - - fn get_auth_header( - &self, - _auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - Ok(vec![]) - } - - fn build_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: netcetera::NetceteraErrorResponse = res - .response - .parse_struct("NetceteraErrorResponse") - .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.error_details.error_code, - message: response.error_details.error_description, - reason: response.error_details.error_detail, - attempt_status: None, - connector_transaction_id: None, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - }) - } -} - -impl ConnectorValidation for Netcetera {} - -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Netcetera -{ -} - -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Netcetera -{ -} - -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Netcetera -{ -} - -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Netcetera -{ -} - -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Netcetera -{ -} - -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Netcetera -{ -} - -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Netcetera -{ -} - -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Netcetera -{ -} - -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Netcetera -{ -} - -#[async_trait::async_trait] -impl api::IncomingWebhook for Netcetera { - fn get_webhook_object_reference_id( - &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { - let webhook_body: netcetera::ResultsResponseData = request - .body - .parse_struct("netcetera ResultsResponseData") - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - Ok(api::webhooks::ObjectReferenceId::ExternalAuthenticationID( - api::webhooks::AuthenticationIdType::ConnectorAuthenticationId( - webhook_body.three_ds_server_trans_id, - ), - )) - } - - fn get_webhook_event_type( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Ok(api::IncomingWebhookEvent::ExternalAuthenticationARes) - } - - fn get_webhook_resource_object( - &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - let webhook_body_value: netcetera::ResultsResponseData = request - .body - .parse_struct("netcetera ResultsResponseDatae") - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - Ok(Box::new(webhook_body_value)) - } - - fn get_external_authentication_details( - &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<ExternalAuthenticationPayload, errors::ConnectorError> { - let webhook_body: netcetera::ResultsResponseData = request - .body - .parse_struct("netcetera ResultsResponseData") - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - Ok(ExternalAuthenticationPayload { - trans_status: webhook_body - .trans_status - .unwrap_or(common_enums::TransactionStatus::InformationOnly), - authentication_value: webhook_body.authentication_value, - eci: webhook_body.eci, - }) - } -} - -fn build_endpoint( - base_url: &str, - connector_metadata: &Option<common_utils::pii::SecretSerdeValue>, -) -> CustomResult<String, errors::ConnectorError> { - let metadata = netcetera::NetceteraMetaData::try_from(connector_metadata)?; - let endpoint_prefix = metadata.endpoint_prefix; - Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix)) -} - -impl api::ConnectorPreAuthentication for Netcetera {} -impl api::ConnectorPreAuthenticationVersionCall for Netcetera {} -impl api::ExternalAuthentication for Netcetera {} -impl api::ConnectorAuthentication for Netcetera {} -impl api::ConnectorPostAuthentication for Netcetera {} - -impl - ConnectorIntegration< - api::PreAuthentication, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, - > for Netcetera -{ - fn get_headers( - &self, - req: &types::authentication::PreAuthNRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - req: &types::authentication::PreAuthNRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; - Ok(format!("{}/3ds/versioning", base_url,)) - } - - fn get_request_body( - &self, - req: &types::authentication::PreAuthNRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = netcetera::NetceteraRouterData::try_from((0, req))?; - let req_obj = - netcetera::NetceteraPreAuthenticationRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(req_obj))) - } - - fn build_request( - &self, - req: &types::authentication::PreAuthNRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let netcetera_auth_type = netcetera::NetceteraAuthType::try_from(&req.connector_auth_type)?; - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url( - &types::authentication::ConnectorPreAuthenticationType::get_url( - self, req, connectors, - )?, - ) - .attach_default_headers() - .headers( - types::authentication::ConnectorPreAuthenticationType::get_headers( - self, req, connectors, - )?, - ) - .set_body( - types::authentication::ConnectorPreAuthenticationType::get_request_body( - self, req, connectors, - )?, - ) - .add_certificate(Some(netcetera_auth_type.certificate)) - .add_certificate_key(Some(netcetera_auth_type.private_key)) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::authentication::PreAuthNRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::authentication::PreAuthNRouterData, errors::ConnectorError> { - let response: netcetera::NetceteraPreAuthenticationResponse = res - .response - .parse_struct("netcetera NetceteraPreAuthenticationResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl - ConnectorIntegration< - api::Authentication, - types::authentication::ConnectorAuthenticationRequestData, - types::authentication::AuthenticationResponseData, - > for Netcetera -{ - fn get_headers( - &self, - req: &types::authentication::ConnectorAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - req: &types::authentication::ConnectorAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; - Ok(format!("{}/3ds/authentication", base_url,)) - } - - fn get_request_body( - &self, - req: &types::authentication::ConnectorAuthenticationRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = netcetera::NetceteraRouterData::try_from(( - &self.get_currency_unit(), - req.request - .currency - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "currency", - })?, - req.request - .amount - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "amount", - })?, - req, - ))?; - let req_obj = netcetera::NetceteraAuthenticationRequest::try_from(&connector_router_data); - Ok(RequestContent::Json(Box::new(req_obj?))) - } - - fn build_request( - &self, - req: &types::authentication::ConnectorAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let netcetera_auth_type = netcetera::NetceteraAuthType::try_from(&req.connector_auth_type)?; - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url( - &types::authentication::ConnectorAuthenticationType::get_url( - self, req, connectors, - )?, - ) - .attach_default_headers() - .headers( - types::authentication::ConnectorAuthenticationType::get_headers( - self, req, connectors, - )?, - ) - .set_body( - types::authentication::ConnectorAuthenticationType::get_request_body( - self, req, connectors, - )?, - ) - .add_certificate(Some(netcetera_auth_type.certificate)) - .add_certificate_key(Some(netcetera_auth_type.private_key)) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::authentication::ConnectorAuthenticationRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult< - types::authentication::ConnectorAuthenticationRouterData, - errors::ConnectorError, - > { - let response: netcetera::NetceteraAuthenticationResponse = res - .response - .parse_struct("NetceteraAuthenticationResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl - ConnectorIntegration< - api::PostAuthentication, - types::authentication::ConnectorPostAuthenticationRequestData, - types::authentication::AuthenticationResponseData, - > for Netcetera -{ -} - -impl - ConnectorIntegration< - api::PreAuthenticationVersionCall, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, - > for Netcetera -{ -} - -impl ConnectorSpecifications for Netcetera {} diff --git a/crates/router/src/connector/plaid.rs b/crates/router/src/connector/plaid.rs deleted file mode 100644 index b0bb40fe8a5..00000000000 --- a/crates/router/src/connector/plaid.rs +++ /dev/null @@ -1,463 +0,0 @@ -pub mod transformers; - -use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}; -use error_stack::ResultExt; -use transformers as plaid; - -use crate::{ - configs::settings, - connector::utils as connector_utils, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, - }, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, RequestContent, Response, - }, - utils::BytesExt, -}; - -#[derive(Clone)] -pub struct Plaid { - amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), -} - -impl Plaid { - pub fn new() -> &'static Self { - &Self { - amount_converter: &FloatMajorUnitForConnector, - } - } -} - -impl api::Payment for Plaid {} -impl api::PaymentSession for Plaid {} -impl api::ConnectorAccessToken for Plaid {} -impl api::MandateSetup for Plaid {} -impl api::PaymentAuthorize for Plaid {} -impl api::PaymentSync for Plaid {} -impl api::PaymentCapture for Plaid {} -impl api::PaymentVoid for Plaid {} -impl api::Refund for Plaid {} -impl api::RefundExecute for Plaid {} -impl api::RefundSync for Plaid {} -impl api::PaymentToken for Plaid {} -impl api::PaymentsPostProcessing for Plaid {} - -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Plaid -{ - // Not Implemented (R) -} - -impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid -where - Self: ConnectorIntegration<Flow, Request, Response>, -{ - fn build_headers( - &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - self.get_content_type().to_string().into(), - )]; - let mut auth = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut auth); - Ok(header) - } -} - -impl ConnectorCommon for Plaid { - fn id(&self) -> &'static str { - "plaid" - } - - fn get_currency_unit(&self) -> api::CurrencyUnit { - api::CurrencyUnit::Base - } - - fn common_get_content_type(&self) -> &'static str { - "application/json" - } - - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { - connectors.plaid.base_url.as_ref() - } - - fn get_auth_header( - &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - let auth = plaid::PlaidAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - let client_id = auth.client_id.into_masked(); - let secret = auth.secret.into_masked(); - - Ok(vec![ - ("PLAID-CLIENT-ID".to_string(), client_id), - ("PLAID-SECRET".to_string(), secret), - ]) - } - - fn build_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: plaid::PlaidErrorResponse = - res.response - .parse_struct("PlaidErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - - Ok(ErrorResponse { - status_code: res.status_code, - code: response - .error_code - .unwrap_or(crate::consts::NO_ERROR_CODE.to_string()), - message: response.error_message, - reason: response.display_message, - attempt_status: None, - connector_transaction_id: None, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - }) - } -} - -impl ConnectorValidation for Plaid { - //TODO: implement functions when support enabled -} - -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Plaid -{ - //TODO: implement sessions flow -} - -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Plaid -{ -} - -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Plaid -{ -} - -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Plaid -{ - fn get_headers( - &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}/payment_initiation/payment/create", - self.base_url(connectors) - )) - } - - fn get_request_body( - &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( - self.amount_converter, - req.request.minor_amount, - req.request.currency, - )?; - let connector_router_data = plaid::PlaidRouterData::from((amount, req)); - let connector_req = plaid::PlaidPaymentsRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) - } - - fn build_request( - &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) - .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( - self, req, connectors, - )?) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::PaymentsAuthorizeRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: plaid::PlaidPaymentsResponse = res - .response - .parse_struct("PlaidPaymentsResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Plaid -{ - fn get_headers( - &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_request_body( - &self, - req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = plaid::PlaidSyncRequest::try_from(req)?; - Ok(RequestContent::Json(Box::new(connector_req))) - } - - fn get_url( - &self, - _req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}/payment_initiation/payment/get", - self.base_url(connectors) - )) - } - - fn build_request( - &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) - .set_body(types::PaymentsSyncType::get_request_body( - self, req, connectors, - )?) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::PaymentsSyncRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - let response: plaid::PlaidSyncResponse = res - .response - .parse_struct("PlaidSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl - ConnectorIntegration< - api::PostProcessing, - types::PaymentsPostProcessingData, - types::PaymentsResponseData, - > for Plaid -{ - fn get_headers( - &self, - req: &types::PaymentsPostProcessingRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - _req: &types::PaymentsPostProcessingRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}/link/token/create", self.base_url(connectors))) - } - - fn get_request_body( - &self, - req: &types::PaymentsPostProcessingRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = plaid::PlaidLinkTokenRequest::try_from(req)?; - Ok(RequestContent::Json(Box::new(connector_req))) - } - - fn build_request( - &self, - req: &types::PaymentsPostProcessingRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsPostProcessingType::get_url( - self, req, connectors, - )?) - .attach_default_headers() - .headers(types::PaymentsPostProcessingType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsPostProcessingType::get_request_body( - self, req, connectors, - )?) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::PaymentsPostProcessingRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::PaymentsPostProcessingRouterData, errors::ConnectorError> { - let response: plaid::PlaidLinkTokenResponse = res - .response - .parse_struct("PlaidLinkTokenResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Plaid -{ -} - -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Plaid -{ -} - -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Plaid {} - -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Plaid {} - -#[async_trait::async_trait] -impl api::IncomingWebhook for Plaid { - fn get_webhook_object_reference_id( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err((errors::ConnectorError::WebhooksNotImplemented).into()) - } - - fn get_webhook_event_type( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err((errors::ConnectorError::WebhooksNotImplemented).into()) - } - - fn get_webhook_resource_object( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err((errors::ConnectorError::WebhooksNotImplemented).into()) - } -} - -impl ConnectorSpecifications for Plaid {} diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 1c071a10e3d..e0034a63335 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1222,66 +1222,6 @@ impl PaymentsPostSessionTokensRequestData for types::PaymentsPostSessionTokensDa } } -#[cfg(feature = "payouts")] -pub trait CustomerDetails { - fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError>; - fn get_customer_name( - &self, - ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>; - fn get_customer_email(&self) -> Result<Email, errors::ConnectorError>; - fn get_customer_phone( - &self, - ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>; - fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError>; -} - -#[cfg(feature = "payouts")] -impl CustomerDetails for types::CustomerDetails { - fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError> { - self.customer_id - .clone() - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "customer_id", - }) - } - - fn get_customer_name( - &self, - ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> { - self.name - .clone() - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "customer_name", - }) - } - - fn get_customer_email(&self) -> Result<Email, errors::ConnectorError> { - self.email - .clone() - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "customer_email", - }) - } - - fn get_customer_phone( - &self, - ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> { - self.phone - .clone() - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "customer_phone", - }) - } - - fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError> { - self.phone_country_code - .clone() - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "customer_phone_country_code", - }) - } -} - pub trait PaymentsCancelRequestData { fn get_amount(&self) -> Result<i64, Error>; fn get_currency(&self) -> Result<enums::Currency, Error>; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 07184065c1f..c8738fa1203 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -14,7 +14,6 @@ use diesel_models::configs; #[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))] use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge}; use error_stack::{report, FutureExt, ResultExt}; -use hyperswitch_connectors::connectors::{chargebee, recurly}; use hyperswitch_domain_models::merchant_connector_account::{ FromRequestEncryptableMerchantConnectorAccount, UpdateEncryptableMerchantConnectorAccount, }; diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 5fc4959bef2..68daf6f1531 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -218,11 +218,6 @@ impl<const T: u8> } default_imp_for_complete_authorize!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -256,11 +251,6 @@ impl<const T: u8> { } default_imp_for_webhook_source_verification!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -296,11 +286,6 @@ impl<const T: u8> } default_imp_for_create_customer!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -337,11 +322,6 @@ impl<const T: u8> services::ConnectorRedirectResponse for connector::DummyConnec } default_imp_for_connector_redirect_response!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -360,11 +340,6 @@ macro_rules! default_imp_for_connector_request_id { impl<const T: u8> api::ConnectorTransactionId for connector::DummyConnector<T> {} default_imp_for_connector_request_id!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -403,11 +378,6 @@ impl<const T: u8> } default_imp_for_accept_dispute!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -465,11 +435,6 @@ impl<const T: u8> } default_imp_for_file_upload!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -504,11 +469,6 @@ impl<const T: u8> } default_imp_for_submit_evidence!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -543,11 +503,6 @@ impl<const T: u8> } default_imp_for_defend_dispute!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -598,11 +553,6 @@ impl<const T: u8> } default_imp_for_pre_processing_steps!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -623,11 +573,7 @@ impl<const T: u8> } default_imp_for_post_processing_steps!( - connector::Adyenplatform, connector::Stripe, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -646,9 +592,6 @@ macro_rules! default_imp_for_payouts { impl<const T: u8> Payouts for connector::DummyConnector<T> {} default_imp_for_payouts!( - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -683,10 +626,6 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_create!( - connector::Adyenplatform, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -721,11 +660,6 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_retrieve!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -765,10 +699,6 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_eligibility!( - connector::Adyenplatform, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -804,9 +734,6 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_fulfill!( - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -841,10 +768,6 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_cancel!( - connector::Adyenplatform, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -879,10 +802,6 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_quote!( - connector::Adyenplatform, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -918,10 +837,6 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_recipient!( - connector::Adyenplatform, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -959,11 +874,6 @@ impl<const T: u8> #[cfg(feature = "payouts")] default_imp_for_payouts_recipient_account!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -998,11 +908,6 @@ impl<const T: u8> } default_imp_for_approve!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1038,11 +943,6 @@ impl<const T: u8> } default_imp_for_reject!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1064,11 +964,6 @@ impl<const T: u8> api::FraudCheck for connector::DummyConnector<T> {} #[cfg(feature = "frm")] default_imp_for_fraud_check!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, @@ -1105,11 +1000,6 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_sale!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, @@ -1146,11 +1036,6 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_checkout!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, @@ -1187,11 +1072,6 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_transaction!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, @@ -1228,11 +1108,6 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_fulfillment!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, @@ -1269,11 +1144,6 @@ impl<const T: u8> #[cfg(feature = "frm")] default_imp_for_frm_record_return!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, @@ -1308,11 +1178,6 @@ impl<const T: u8> } default_imp_for_incremental_authorization!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1346,11 +1211,6 @@ impl<const T: u8> { } default_imp_for_revoking_mandates!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1444,9 +1304,6 @@ impl<const T: u8> { } default_imp_for_connector_authentication!( - connector::Adyenplatform, - connector::Ebanx, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Wellsfargopayout, @@ -1478,11 +1335,6 @@ impl<const T: u8> { } default_imp_for_authorize_session_token!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1516,11 +1368,6 @@ impl<const T: u8> } default_imp_for_calculate_tax!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1554,11 +1401,6 @@ impl<const T: u8> } default_imp_for_session_update!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1592,11 +1434,6 @@ impl<const T: u8> } default_imp_for_post_session_tokens!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1630,11 +1467,6 @@ impl<const T: u8> } default_imp_for_update_metadata!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -1670,11 +1502,6 @@ impl<const T: u8> } default_imp_for_uas_pre_authentication!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1708,11 +1535,6 @@ impl<const T: u8> } default_imp_for_uas_post_authentication!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1735,11 +1557,6 @@ macro_rules! default_imp_for_uas_authentication_confirmation { } default_imp_for_uas_authentication_confirmation!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1786,11 +1603,6 @@ impl<const T: u8> } default_imp_for_uas_authentication!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1919,12 +1731,6 @@ macro_rules! default_imp_for_revenue_recovery { impl<const T: u8> api::RevenueRecovery for connector::DummyConnector<T> {} default_imp_for_revenue_recovery! { - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, - connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1962,11 +1768,6 @@ impl<const T: u8> #[cfg(all(feature = "v2", feature = "revenue_recovery"))] default_imp_for_billing_connector_payment_sync!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -2004,11 +1805,6 @@ impl<const T: u8> } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] default_imp_for_revenue_recovery_record_back!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -2046,11 +1842,6 @@ impl<const T: u8> } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] default_imp_for_billing_connector_invoice_sync!( - connector::Adyenplatform, - connector::Ebanx, - connector::Gpayments, - connector::Netcetera, - connector::Plaid, connector::Signifyd, connector::Stripe, connector::Threedsecureio,
2025-04-28T06:27:15Z
## 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 --> Moving connectors from `crates/router` to `crates/hyperswitch_connectors` 1. adyenplatform 2. ebanx 3. gpayments 4. netcetera 5. plaid issue: https://github.com/juspay/hyperswitch/issues/7916 ### 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` 7. `crates/router/src/configs` 8. `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)? --> **PLAID** REF PR : https://github.com/juspay/hyperswitch/pull/3952 1. create plaid MCA ```sh curl --location 'http://localhost:8080/account/merchant_1745827786/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: integ-custom' \ --header 'api-key: dev_3MQvYMIeRXwga5C0QQaHBqi6RzjIbIEgcenajXpGnqONwMEcwkx4SHzvduOEOTjF' \ --data '{ "connector_type": "payment_processor", "connector_name": "plaid", "connector_account_details": { "auth_type": "BodyKey", "api_key": "***", "key1": "***" }, "payment_methods_enabled": [ { "payment_method": "open_banking", "payment_method_types": [ { "payment_method_type": "open_banking_pis", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": { "type": "enable_only", "list": [ "EUR", "GBP" ] }, "accepted_countries": null, "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": null, "metadata": { "city": "NY", "unit": "246" }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": null, "business_label": null, "business_sub_label": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": { "open_banking_recipient_data": { "account_data": { "bacs": { "account_number": "55779911", "sort_code": "200000", "name": "merchant_name", "connector_recipient_id": "recipient-id-sandbox-45beb880-9e3d-4ae3-927b-052f5610fd74" } } } } }’ ``` 2. create payment ```sh curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_3MQvYMIeRXwga5C0QQaHBqi6RzjIbIEgcenajXpGnqONwMEcwkx4SHzvduOEOTjF' \ --data-raw '{ "amount": 200, "currency": "GBP", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "GB", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "GB", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }’ ``` SUCCESS RESPONSE ```json { "payment_id": "pay_YHCSrBabp6msKIdaaMaI", "merchant_id": "merchant_1745827786", "status": "requires_payment_method", "amount": 200, "net_amount": 200, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_YHCSrBabp6msKIdaaMaI_secret_kUrGl5b5l986f5dcErNV", "created": "2025-04-28T08:10:06.811Z", "currency": "GBP", "customer_id": null, "customer": { "id": null, "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": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "GB", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "GB", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_J7WGw473DjsyTN52d0hJ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-28T08:25:06.811Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-28T08:10:06.841Z", "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 } ``` 3. CONFIRM ```sh curl --location 'http://localhost:8080/payments/pay_YHCSrBabp6msKIdaaMaI/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_3MQvYMIeRXwga5C0QQaHBqi6RzjIbIEgcenajXpGnqONwMEcwkx4SHzvduOEOTjF' \ --data '{ "payment_method": "open_banking", "payment_method_type": "open_banking_pis", "payment_method_data": { "open_banking": { "open_banking_pis": {} } } }’ ``` response Successful response will have status as requires_customer_action and next_action as third_party_sdk_session_token - ```json { "payment_id": "pay_YHCSrBabp6msKIdaaMaI", "merchant_id": "merchant_1745827786", "status": "requires_customer_action", "amount": 200, "net_amount": 200, "shipping_cost": null, "amount_capturable": 200, "amount_received": null, "connector": "plaid", "client_secret": "pay_YHCSrBabp6msKIdaaMaI_secret_kUrGl5b5l986f5dcErNV", "created": "2025-04-28T08:10:06.811Z", "currency": "GBP", "customer_id": null, "customer": { "id": null, "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": "open_banking", "payment_method_data": { "open_banking": { "open_banking_pis": {} }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "GB", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "GB", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "third_party_sdk_session_token", "session_token": { "wallet_name": "open_banking", "open_banking_session_token": "link-sandbox-13e756c7-45e2-4841-b10d-fd97627ba501" } }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "open_banking_pis", "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": "payment-id-sandbox-2d044d64-b713-433d-b249-f99d47c1fbac", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "payment-id-sandbox-2d044d64-b713-433d-b249-f99d47c1fbac", "payment_link": null, "profile_id": "pro_J7WGw473DjsyTN52d0hJ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_3r6Sr9CClmCPCuXIEzKV", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-28T08:25:06.811Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-28T08:21:50.132Z", "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 } ``` NETCETERA 1. CREATE Netcetera auth processor and checkout payment processor 2. Update Business profile for auth flow ```sh curl --location 'http://localhost:8080/account/merchant_1745840350/business_profile/pro_5ue8hhxsHkXzCanhT2CW' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_5gY5nna8FN6u9l7H7ilO3ksCW3LkoypGaOLhZV5ScNxfw1lw8xksxWyIFsZsZVTD' \ --data '{ "profile_name": "grocery", "authentication_connector_details": { "authentication_connectors": [ "netcetera" ], "three_ds_requestor_url": "https://3dss-pp-prev-ndm.acquiring.test.netcetera.com/acs/3ds-method" } }' ``` 3. create payment whith `"request_external_three_ds_authentication": true` ```sh curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_5gY5nna8FN6u9l7H7ilO3ksCW3LkoypGaOLhZV5ScNxfw1lw8xksxWyIFsZsZVTD' \ --data-raw '{ "amount": 100, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 100, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" }, "phone": { "number": "123456789", "country_code": "12" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" }, "phone": { "number": "123456789", "country_code": "12" } }, "request_external_three_ds_authentication": true, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response `"status"="requires_payment_method",` 4. Payment confirm ```sh curl --location 'http://localhost:8080/payments/pay_re3vpR4Dwn6MNmO2xogp/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_5gY5nna8FN6u9l7H7ilO3ksCW3LkoypGaOLhZV5ScNxfw1lw8xksxWyIFsZsZVTD' \ --data '{ "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": "115.99.183.2" }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4929251897047956", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } }'` Response : ```json { "payment_id": "pay_re3vpR4Dwn6MNmO2xogp", "merchant_id": "merchant_1745840350", "status": "requires_customer_action", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 100, "amount_received": null, "connector": "checkout", "client_secret": "pay_re3vpR4Dwn6MNmO2xogp_secret_q1EZvfdAPSkIZY6eCXhf", "created": "2025-04-28T12:47:07.085Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "7956", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "492925", "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_Oj4F2UQ4PIN3h9uejq9S", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": "123456789", "country_code": "12" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": { "number": "123456789", "country_code": "12" }, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "three_ds_invoke", "three_ds_data": { "three_ds_authentication_url": "http://localhost:8080/payments/pay_re3vpR4Dwn6MNmO2xogp/3ds/authentication", "three_ds_authorize_url": "http://localhost:8080/payments/pay_re3vpR4Dwn6MNmO2xogp/merchant_1745840350/authorize/checkout", "three_ds_method_details": { "three_ds_method_key": "threeDSMethodData", "three_ds_method_data_submission": true, "three_ds_method_data": "eyJ0aHJlZURTTWV0aG9kTm90aWZpY2F0aW9uVVJMIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS8zZHMtbWV0aG9kLW5vdGlmaWNhdGlvbi11cmwiLCJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IjY5YjU4NzlmLTIwYWEtNGIxMi1hNjFkLTg1YTg0NzZmZjdmNyJ9", "three_ds_method_url": "https://ndm-prev.3dss-non-prod.cloud.netcetera.com/acs/3ds-method" }, "poll_config": { "poll_id": "external_authentication_pay_re3vpR4Dwn6MNmO2xogp", "delay_in_secs": 2, "frequency": 5 }, "message_version": "2.3.1", "directory_server_id": "A000000003" } }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_5ue8hhxsHkXzCanhT2CW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_s8Vw96XBCTmvBGMGqEj5", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": { "authentication_flow": null, "electronic_commerce_indicator": null, "status": "pending", "ds_transaction_id": "69b5879f-20aa-4b12-a61d-85a8476ff7f7", "version": "2.3.1", "error_code": null, "error_message": null }, "external_3ds_authentication_attempted": true, "expires_on": "2025-04-28T13:02:07.085Z", "fingerprint": null, "browser_info": { "os_type": null, "language": "nl-NL", "time_zone": 0, "ip_address": "115.99.183.2", "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_method_id": null, "payment_method_status": null, "updated": "2025-04-28T12:47:19.403Z", "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 } ``` AYDENPLATFORM Create payout - adyenplatform supports only SEPA - https://github.com/juspay/hyperswitch-cloud/issues/5414 ```sh curl --location 'http://localhost:8080/payouts/create' \ --header 'x-feature: integ-custom' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_5gY5nna8FN6u9l7H7ilO3ksCW3LkoypGaOLhZV5ScNxfw1lw8xksxWyIFsZsZVTD' \ --data-raw '{ "amount": 100, "currency": "EUR", "customer_id": "cus_BoR4qowJ8Fa872dKgQLD", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payout request", "payout_type": "bank", "priority": "regular", "payout_method_data": { "bank": { "iban": "NL57INGB4654188101" } }, "connector": [ "adyenplatform" ], "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" } }, "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "confirm": true, "auto_fulfill": false }' ``` Response ```json { "payout_id": "8fac3092-81e4-4936-b619-713de4281e36", "merchant_id": "merchant_1745840350", "amount": 100, "currency": "EUR", "connector": "adyenplatform", "payout_type": "bank", "payout_method_data": { "bank": { "iban": "NL57I********88101", "bank_name": null, "bank_country_code": null, "bank_city": null, "bic": null } }, "billing": { "address": { "city": "Hoogeveen", "country": "NL", "line1": "Raadhuisplein", "line2": "92", "line3": null, "zip": "7901 BW", "state": "FL", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "0650242319", "country_code": "+31" }, "email": null }, "auto_fulfill": false, "customer_id": "cus_BoR4qowJ8Fa872dKgQLD", "customer": { "id": "cus_BoR4qowJ8Fa872dKgQLD", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "client_secret": "payout_8fac3092-81e4-4936-b619-713de4281e36_secret_LMTGxKqCY3DViNkN3Y5x", "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_ZnBgWE1jKXg7Ogzvs0Ha", "status": "requires_fulfillment", "error_message": null, "error_code": null, "profile_id": "pro_5ue8hhxsHkXzCanhT2CW", "created": "2025-04-29T06:00:21.535Z", "connector_transaction_id": null, "priority": "regular", "payout_link": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "unified_code": null, "unified_message": null, "payout_method_id": null } ``` Fulfill ```sh curl --location 'http://localhost:8080/payouts/8fac3092-81e4-4936-b619-713de4281e36/fulfill' \ --header 'x-feature: integ-custom' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_5gY5nna8FN6u9l7H7ilO3ksCW3LkoypGaOLhZV5ScNxfw1lw8xksxWyIFsZsZVTD' \ --data '{ "payout_id":"8fac3092-81e4-4936-b619-713de4281e36" }' ``` ```sh { "payout_id": "8fac3092-81e4-4936-b619-713de4281e36", "merchant_id": "merchant_1745840350", "amount": 100, "currency": "EUR", "connector": "adyenplatform", "payout_type": "bank", "payout_method_data": { "bank": { "iban": "NL57I********88101", "bank_name": null, "bank_country_code": null, "bank_city": null, "bic": null } }, "billing": { "address": { "city": "Hoogeveen", "country": "NL", "line1": "Raadhuisplein", "line2": "92", "line3": null, "zip": "7901 BW", "state": "FL", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "0650242319", "country_code": "+31" }, "email": null }, "auto_fulfill": false, "customer_id": "cus_BoR4qowJ8Fa872dKgQLD", "customer": { "id": "cus_BoR4qowJ8Fa872dKgQLD", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "client_secret": "payout_8fac3092-81e4-4936-b619-713de4281e36_secret_LMTGxKqCY3DViNkN3Y5x", "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_ZnBgWE1jKXg7Ogzvs0Ha", "status": "failed", "error_message": "Unauthorized", "error_code": "00_401", "profile_id": "pro_5ue8hhxsHkXzCanhT2CW", "created": "2025-04-29T06:00:21.535Z", "connector_transaction_id": null, "priority": "regular", "payout_link": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "unified_code": null, "unified_message": null, "payout_method_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.114.0
31e109a9a1367ef53786c146604b31fca69b15ef
31e109a9a1367ef53786c146604b31fca69b15ef
juspay/hyperswitch
juspay__hyperswitch-7908
Bug: [REFACTOR] Refactor Merchant Payment Method List Refactor Merchant PML to list the wallets even after they are saved by the customer
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 2643b97904c..fc3ff05d864 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1922,7 +1922,10 @@ pub enum PaymentMethodType { impl PaymentMethodType { pub fn should_check_for_customer_saved_payment_method_type(self) -> bool { - matches!(self, Self::ApplePay | Self::GooglePay | Self::SamsungPay) + matches!( + self, + Self::ApplePay | Self::GooglePay | Self::SamsungPay | Self::Paypal | Self::Klarna + ) } pub fn to_display_name(&self) -> String { let display_name = match self { diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index e9fefffbb07..14744cd2d56 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3459,61 +3459,6 @@ pub async fn list_payment_methods( response ); - // Filter out wallet payment method from mca if customer has already saved it - customer - .as_ref() - .async_map(|customer| async { - let wallet_pm_exists = response - .iter() - .any(|mca| mca.payment_method == enums::PaymentMethod::Wallet); - if wallet_pm_exists { - match db - .find_payment_method_by_customer_id_merchant_id_status( - &((&state).into()), - &key_store, - &customer.customer_id, - merchant_account.get_id(), - common_enums::PaymentMethodStatus::Active, - None, - merchant_account.storage_scheme, - ) - .await - { - Ok(customer_payment_methods) => { - let customer_wallet_pm = customer_payment_methods - .iter() - .filter(|cust_pm| { - cust_pm.get_payment_method_type() == Some(enums::PaymentMethod::Wallet) - }) - .collect::<Vec<_>>(); - - response.retain(|mca| { - !(mca.payment_method == enums::PaymentMethod::Wallet - && customer_wallet_pm.iter().any(|cust_pm| { - cust_pm.get_payment_method_subtype() == Some(mca.payment_method_type) - })) - }); - - logger::debug!("Filtered out wallet payment method from mca since customer has already saved it"); - Ok(()) - } - Err(error) => { - if error.current_context().is_db_not_found() { - Ok(()) - } else { - Err(error) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to find payment methods for a customer") - } - } - } - } else { - Ok(()) - } - }) - .await - .transpose()?; - let mut pmt_to_auth_connector: HashMap< enums::PaymentMethod, HashMap<enums::PaymentMethodType, String>,
2025-04-22T08:35:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Earlier we used to support filtering of wallet payment methods for customer pml, if it has been saved by the merchant via off- session payments once , the changes were made in the following [PR](https://github.com/juspay/hyperswitch/pull/4038) - In this PR we are reverting the logic , the decision was taken to show the wallets in merchant pml even though a single entry in customer pml is present for that particular wallets , - internally the decision was taken to allow overriding of the wallets connector mandate id for the customer for off-session payments ### 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 MA and an MCA with wallets -Create a payment and Save one wallet (eg: Paypal) - Create a new payment intent - List the Merchant PML again, Paypal would still be there ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "paypal", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "paypal" ] }, { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "paypal" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "shipping.address.first_name": { "required_field": "shipping.address.first_name", "display_name": "shipping_first_name", "field_type": "user_shipping_name", "value": "PiX" }, "shipping.address.last_name": { "required_field": "shipping.address.last_name", "display_name": "shipping_last_name", "field_type": "user_shipping_name", "value": null }, "shipping.address.city": { "required_field": "shipping.address.city", "display_name": "city", "field_type": "user_shipping_address_city", "value": "San Fransico" }, "shipping.address.line1": { "required_field": "shipping.address.line1", "display_name": "line1", "field_type": "user_shipping_address_line1", "value": "1467" }, "shipping.address.country": { "required_field": "shipping.address.country", "display_name": "country", "field_type": { "user_shipping_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "shipping.address.state": { "required_field": "shipping.address.state", "display_name": "state", "field_type": "user_shipping_address_state", "value": "California" }, "shipping.address.zip": { "required_field": "shipping.address.zip", "display_name": "zip", "field_type": "user_shipping_address_pincode", "value": "94122" } }, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "paypal" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "paypal" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "is_tax_calculation_enabled": false } ``` ## 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.113.0
9e82c40eed78ddabcbf0b0531b4fbbcc44d9142a
9e82c40eed78ddabcbf0b0531b4fbbcc44d9142a
juspay/hyperswitch
juspay__hyperswitch-7904
Bug: [FEATURE] Tokenization service ### Feature Description Need of generic tokenization service is required which can be used to tokenize any data which could be used by the consumer in various other services, one of the usecases is proxy payments ### Possible Implementation Use the locker to store the tokenized data and give out reference to that data to user through which it can be used in any place. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/api-reference-v2/api-reference/tokenization/tokenization--create.mdx b/api-reference-v2/api-reference/tokenization/tokenization--create.mdx new file mode 100644 index 00000000000..a0002736185 --- /dev/null +++ b/api-reference-v2/api-reference/tokenization/tokenization--create.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/tokenize +--- \ No newline at end of file diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json index e56b9d684ec..8c49d3dd708 100644 --- a/api-reference-v2/mint.json +++ b/api-reference-v2/mint.json @@ -146,6 +146,10 @@ { "group": "Proxy", "pages": ["api-reference/proxy/proxy"] + }, + { + "group": "Tokenization", + "pages": ["api-reference/tokenization/tokenization--create"] } ], "footerSocials": { diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 00e3e7bc4ff..2347c6f9f49 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3532,6 +3532,67 @@ } ] } + }, + "/v2/tokenize": { + "post": { + "tags": [ + "Tokenization" + ], + "operationId": "create_token_vault_api", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GenericTokenizationRequest" + }, + "examples": { + "Create a token with customer_id": { + "value": { + "customer_id": "12345_cus_0196d94b9c207333a297cbcf31f2e8c8", + "token_request": { + "payment_method_data": { + "card": { + "card_holder_name": "test name" + } + } + } + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Token created successfully", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GenericTokenizationResponse" + } + } + } + }, + "400": { + "description": "Invalid request" + }, + "401": { + "description": "Unauthorized" + }, + "500": { + "description": "Internal server error" + } + }, + "security": [ + { + "ephemeral_key": [] + }, + { + "api_key": [] + } + ] + } } }, "components": { @@ -11032,6 +11093,50 @@ } } }, + "GenericTokenizationRequest": { + "type": "object", + "required": [ + "customer_id", + "token_request" + ], + "properties": { + "customer_id": { + "type": "string", + "description": "Customer ID for which the tokenization is requested", + "example": "12345_cus_01926c58bc6e77c09e809964e72af8c8" + }, + "token_request": { + "type": "object", + "description": "Request for tokenization which contains the data to be tokenized" + } + } + }, + "GenericTokenizationResponse": { + "type": "object", + "required": [ + "id", + "created_at", + "flag" + ], + "properties": { + "id": { + "type": "string", + "description": "Unique identifier returned by the tokenization service", + "example": "12345_tok_01926c58bc6e77c09e809964e72af8c8" + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Created time of the tokenization id", + "example": "2024-02-24T11:04:09.922Z" + }, + "flag": { + "type": "string", + "description": "Status of the tokenization id created", + "example": "enabled" + } + } + }, "GiftCardAdditionalData": { "oneOf": [ { @@ -16595,6 +16700,10 @@ "example": 900, "nullable": true, "minimum": 0 + }, + "tokenization_data": { + "description": "Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data", + "nullable": true } } }, @@ -16640,6 +16749,10 @@ ], "nullable": true }, + "tokenization_data": { + "description": "Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data", + "nullable": true + }, "expires_at": { "type": "string", "format": "date-time", @@ -16678,6 +16791,12 @@ }, "description": "The payment method that was created using this payment method session", "nullable": true + }, + "associated_token_id": { + "type": "string", + "description": "The token-id created if there is tokenization_data present", + "example": "12345_tok_01926c58bc6e77c09e809964e72af8c8", + "nullable": true } } }, @@ -16941,6 +17060,10 @@ } ], "nullable": true + }, + "tokenization_data": { + "description": "Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data", + "nullable": true } } }, diff --git a/config/development.toml b/config/development.toml index 7deb3b46992..039bd7c274b 100644 --- a/config/development.toml +++ b/config/development.toml @@ -84,28 +84,8 @@ redis_lock_timeout_in_seconds = 100 redis_ttl_in_seconds = 172800 [jwekey] -vault_encryption_key = """ ------BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwa6siKaSYqD1o4J3AbHq -Km8oVTvep7GoN/C45qY60C7DO72H1O7Ujt6ZsSiK83EyI0CaUg3ORPS3ayobFNmu -zR366ckK8GIf3BG7sVI6u/9751z4OvBHZMM9JFWa7Bx/RCPQ8aeM+iJoqf9auuQm -3NCTlfaZJif45pShswR+xuZTR/bqnsOSP/MFROI9ch0NE7KRogy0tvrZe21lP24i -Ro2LJJG+bYshxBddhxQf2ryJ85+/Trxdu16PunodGzCl6EMT3bvb4ZC41i15omqU -aXXV1Z1wYUhlsO0jyd1bVvjyuE/KE1TbBS0gfR/RkacODmmE2zEdZ0EyyiXwqkmc -oQIDAQAB ------END PUBLIC KEY----- -""" -rust_locker_encryption_key = """ ------BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwa6siKaSYqD1o4J3AbHq -Km8oVTvep7GoN/C45qY60C7DO72H1O7Ujt6ZsSiK83EyI0CaUg3ORPS3ayobFNmu -zR366ckK8GIf3BG7sVI6u/9751z4OvBHZMM9JFWa7Bx/RCPQ8aeM+iJoqf9auuQm -3NCTlfaZJif45pShswR+xuZTR/bqnsOSP/MFROI9ch0NE7KRogy0tvrZe21lP24i -Ro2LJJG+bYshxBddhxQf2ryJ85+/Trxdu16PunodGzCl6EMT3bvb4ZC41i15omqU -aXXV1Z1wYUhlsO0jyd1bVvjyuE/KE1TbBS0gfR/RkacODmmE2zEdZ0EyyiXwqkmc -oQIDAQAB ------END PUBLIC KEY----- -""" +vault_encryption_key = "" +rust_locker_encryption_key = "" vault_private_key = "" tunnel_private_key = "" diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 120e9121388..32a798c3c0b 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -17,13 +17,14 @@ olap = [] openapi = ["common_enums/openapi", "olap", "recon", "dummy_connector", "olap"] recon = [] v1 = ["common_utils/v1"] -v2 = ["common_types/v2", "common_utils/v2", "customer_v2", "refunds_v2"] +v2 = ["common_types/v2", "common_utils/v2", "customer_v2", "refunds_v2", "tokenization_v2"] customer_v2 = ["common_utils/customer_v2"] payment_methods_v2 = ["common_utils/payment_methods_v2", "dep:reqwest"] refunds_v2 = [] dynamic_routing = [] control_center_theme = ["dep:actix-web", "dep:actix-multipart"] revenue_recovery = [] +tokenization_v2 = ["common_utils/tokenization_v2"] [dependencies] actix-multipart = { version = "0.6.1", optional = true } diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 973bdea9eef..e0e57050c4e 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -22,6 +22,8 @@ use common_utils::{ }; use crate::customers::CustomerListRequest; +#[cfg(feature = "tokenization_v2")] +use crate::tokenization; #[allow(unused_imports)] use crate::{ admin::*, @@ -228,3 +230,8 @@ impl ApiEventMetric for PaymentMethodSessionResponse { }) } } +#[cfg(feature = "tokenization_v2")] +impl ApiEventMetric for tokenization::GenericTokenizationRequest {} + +#[cfg(feature = "tokenization_v2")] +impl ApiEventMetric for tokenization::GenericTokenizationResponse {} diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index fa3c34db930..a77baf7d942 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -40,6 +40,8 @@ pub mod refunds; pub mod relay; pub mod routing; pub mod surcharge_decision_configs; +#[cfg(feature = "tokenization_v2")] +pub mod tokenization; pub mod user; pub mod user_role; pub mod verifications; diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 6e9a174c9f6..92761192d1c 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -2861,6 +2861,10 @@ pub struct PaymentMethodSessionRequest { /// If not provided, the session will expire in 15 minutes #[schema(example = 900, default = 900)] pub expires_in: Option<u32>, + + /// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data + #[schema(value_type = Option<serde_json::Value>)] + pub tokenization_data: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] @@ -2877,6 +2881,10 @@ pub struct PaymentMethodsSessionUpdateRequest { /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + + /// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data + #[schema(value_type = Option<serde_json::Value>)] + pub tokenization_data: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] @@ -2941,6 +2949,10 @@ pub struct PaymentMethodSessionResponse { #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + /// Contains data to be passed on to tokenization service ( if present ) to create token_id for given JSON data + #[schema(value_type = Option<serde_json::Value>)] + pub tokenization_data: Option<pii::SecretSerdeValue>, + /// The iso timestamp when the session will expire /// Trying to retrieve the session or any operations on the session after this time will result in an error #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] @@ -2966,6 +2978,10 @@ pub struct PaymentMethodSessionResponse { /// The payment method that was created using this payment method session #[schema(value_type = Option<Vec<String>>)] pub associated_payment_methods: Option<Vec<id_type::GlobalPaymentMethodId>>, + + /// The token-id created if there is tokenization_data present + #[schema(value_type = Option<String>, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")] + pub associated_token_id: Option<id_type::GlobalTokenId>, } #[cfg(feature = "v2")] diff --git a/crates/api_models/src/tokenization.rs b/crates/api_models/src/tokenization.rs new file mode 100644 index 00000000000..5ee044ec1fb --- /dev/null +++ b/crates/api_models/src/tokenization.rs @@ -0,0 +1,30 @@ +use common_enums; +use common_utils::id_type::{GlobalCustomerId, GlobalTokenId}; +use masking::Secret; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; +use utoipa::{schema, ToSchema}; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Debug, Serialize, Deserialize, ToSchema)] +pub struct GenericTokenizationResponse { + /// Unique identifier returned by the tokenization service + #[schema(value_type = String, example = "12345_tok_01926c58bc6e77c09e809964e72af8c8")] + pub id: GlobalTokenId, + /// Created time of the tokenization id + #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] + pub created_at: PrimitiveDateTime, + /// Status of the tokenization id created + #[schema(value_type = String,example = "enabled")] + pub flag: common_enums::TokenizationFlag, +} +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Debug, Serialize, Deserialize, ToSchema)] +pub struct GenericTokenizationRequest { + /// Customer ID for which the tokenization is requested + #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] + pub customer_id: GlobalCustomerId, + /// Request for tokenization which contains the data to be tokenized + #[schema(value_type = Object,example = json!({ "city": "NY", "unit": "245" }))] + pub token_request: masking::Secret<serde_json::Value>, +} diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index b3ab41b020a..0f0064414ca 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -29,7 +29,7 @@ pub mod diesel_exports { DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, - DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, + DbTokenizationFlag as TokenizationFlag, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } @@ -8299,6 +8299,28 @@ pub enum CryptoPadding { ZeroPadding, } +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum TokenizationFlag { + /// Token is active and can be used for payments + Enabled, + /// Token is inactive and cannot be used for payments + Disabled, +} + /// The type of token data to fetch for get-token endpoint #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/common_types/Cargo.toml b/crates/common_types/Cargo.toml index 3f49f546a71..97695cb87d3 100644 --- a/crates/common_types/Cargo.toml +++ b/crates/common_types/Cargo.toml @@ -10,6 +10,7 @@ license.workspace = true default = [] v1 = ["common_utils/v1"] v2 = ["common_utils/v2"] +tokenization_v2 = ["common_utils/tokenization_v2"] [dependencies] diesel = "2.2.3" diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index 4f4322c3ca3..43f28817c7e 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -23,6 +23,7 @@ v2 = [] customer_v2 = [] payment_methods_v2 = [] crypto_openssl = ["dep:openssl"] +tokenization_v2 = [] [dependencies] async-trait = { version = "0.1.79", optional = true } diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index e3eba81b12f..bdbaa1eae6c 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -179,6 +179,10 @@ pub const DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS: i32 = 3600; /// SOAP 1.1 Envelope Namespace pub const SOAP_ENV_NAMESPACE: &str = "http://schemas.xmlsoap.org/soap/envelope/"; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +/// Length of generated tokens +pub const TOKEN_LENGTH: usize = 32; + /// The tag name used for identifying the host in metrics. pub const METRICS_HOST_TAG_NAME: &str = "host"; diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index f7a068b8e49..5ba16ee2c42 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -121,6 +121,10 @@ pub enum ApiEventsType { PaymentMethodSession { payment_method_session_id: id_type::GlobalPaymentMethodSessionId, }, + #[cfg(feature = "v2")] + Token { + token_id: Option<id_type::GlobalTokenId>, + }, ProcessTracker, } diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index 30b6a3888da..34a3844e76b 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -34,6 +34,7 @@ pub use self::global_id::{ payment::{GlobalAttemptId, GlobalPaymentId}, payment_methods::{GlobalPaymentMethodId, GlobalPaymentMethodSessionId}, refunds::GlobalRefundId, + token::GlobalTokenId, CellId, }; pub use self::{ diff --git a/crates/common_utils/src/id_type/global_id.rs b/crates/common_utils/src/id_type/global_id.rs index bb296d7ef1a..b9ed173ce3e 100644 --- a/crates/common_utils/src/id_type/global_id.rs +++ b/crates/common_utils/src/id_type/global_id.rs @@ -2,6 +2,7 @@ pub(super) mod customer; pub(super) mod payment; pub(super) mod payment_methods; pub(super) mod refunds; +pub(super) mod token; use diesel::{backend::Backend, deserialize::FromSql, serialize::ToSql, sql_types}; use error_stack::ResultExt; @@ -27,6 +28,7 @@ pub(crate) enum GlobalEntity { PaymentMethod, Refund, PaymentMethodSession, + Token, } impl GlobalEntity { @@ -38,6 +40,7 @@ impl GlobalEntity { Self::Attempt => "att", Self::Refund => "ref", Self::PaymentMethodSession => "pms", + Self::Token => "tok", } } } diff --git a/crates/common_utils/src/id_type/global_id/token.rs b/crates/common_utils/src/id_type/global_id/token.rs new file mode 100644 index 00000000000..929c03f0959 --- /dev/null +++ b/crates/common_utils/src/id_type/global_id/token.rs @@ -0,0 +1,37 @@ +use error_stack::ResultExt; + +use crate::{errors, generate_id_with_default_len, generate_time_ordered_id_without_prefix, types}; + +crate::global_id_type!( + GlobalTokenId, + "A global id that can be used to identify a token. + +The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`. + +Example: `cell1_tok_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`" +); + +// Database related implementations so that this field can be used directly in the database tables +crate::impl_queryable_id_type!(GlobalTokenId); +crate::impl_to_sql_from_sql_global_id_type!(GlobalTokenId); + +impl GlobalTokenId { + /// Get string representation of the id + pub fn get_string_repr(&self) -> &str { + self.0.get_string_repr() + } + + /// Generate a new GlobalTokenId from a cell id + pub fn generate(cell_id: &crate::id_type::CellId) -> Self { + let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Token); + Self(global_id) + } +} + +impl crate::events::ApiEventMetric for GlobalTokenId { + fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { + Some(crate::events::ApiEventsType::Token { + token_id: Some(self.clone()), + }) + } +} diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index fd0c935035f..759329ba327 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -333,3 +333,10 @@ mod nanoid_tests { assert!(ref_id.is_ok()) } } + +/// Module for tokenization-related functionality +/// +/// This module provides types and functions for handling tokenized payment data, +/// including response structures and token generation utilities. +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub mod tokenization; diff --git a/crates/common_utils/src/tokenization.rs b/crates/common_utils/src/tokenization.rs new file mode 100644 index 00000000000..aa0f3dda8c1 --- /dev/null +++ b/crates/common_utils/src/tokenization.rs @@ -0,0 +1,21 @@ +//! Module for tokenization-related functionality +//! +//! This module provides types and functions for handling tokenized payment data, +//! including response structures and token generation utilities. + +use common_enums::ApiVersion; +use diesel; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; + +use crate::{consts::TOKEN_LENGTH, id_type::GlobalTokenId}; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +/// Generates a new token string +/// +/// # Returns +/// A randomly generated token string of length `TOKEN_LENGTH` +pub fn generate_token() -> String { + use nanoid::nanoid; + nanoid!(TOKEN_LENGTH) +} diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml index e10428c5daf..8f7c5f92908 100644 --- a/crates/diesel_models/Cargo.toml +++ b/crates/diesel_models/Cargo.toml @@ -15,6 +15,7 @@ v2 = ["common_utils/v2", "common_types/v2"] customer_v2 = [] payment_methods_v2 = [] refunds_v2 = [] +tokenization_v2 = [] [dependencies] async-bb8-diesel = "0.2.1" diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index bd710dfdd6b..39ce33a5130 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -23,13 +23,16 @@ pub mod diesel_exports { DbRevenueRecoveryAlgorithmType as RevenueRecoveryAlgorithmType, DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, - DbTotpStatus as TotpStatus, DbTransactionType as TransactionType, - DbUserRoleVersion as UserRoleVersion, DbUserStatus as UserStatus, - DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, + DbTokenizationFlag as TokenizationFlag, DbTotpStatus as TotpStatus, + DbTransactionType as TransactionType, DbUserRoleVersion as UserRoleVersion, + DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } + pub use common_enums::*; use common_utils::pii; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub use common_utils::tokenization; use diesel::{deserialize::FromSqlRow, expression::AsExpression, sql_types::Jsonb}; use router_derive::diesel_enum; use time::PrimitiveDateTime; diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index e5c7aea9d56..e34e7e552d8 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -140,3 +140,6 @@ pub(crate) mod metrics { counter_metric!(DATABASE_CALLS_COUNT, GLOBAL_METER); histogram_metric_f64!(DATABASE_CALL_TIME, GLOBAL_METER); } + +#[cfg(feature = "tokenization_v2")] +pub mod tokenization; diff --git a/crates/diesel_models/src/mod.rs b/crates/diesel_models/src/mod.rs new file mode 100644 index 00000000000..3cdc13b0c8a --- /dev/null +++ b/crates/diesel_models/src/mod.rs @@ -0,0 +1,2 @@ +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub mod tokenization; \ No newline at end of file diff --git a/crates/diesel_models/src/payment_methods_session.rs b/crates/diesel_models/src/payment_methods_session.rs index 250fd44bdbf..037214387a7 100644 --- a/crates/diesel_models/src/payment_methods_session.rs +++ b/crates/diesel_models/src/payment_methods_session.rs @@ -1,3 +1,5 @@ +use common_utils::pii; + #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodSession { @@ -6,11 +8,13 @@ pub struct PaymentMethodSession { pub billing: Option<common_utils::encryption::Encryption>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + pub tokenization_data: Option<pii::SecretSerdeValue>, pub return_url: Option<common_utils::types::Url>, #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_at: time::PrimitiveDateTime, pub associated_payment_methods: Option<Vec<common_utils::id_type::GlobalPaymentMethodId>>, pub associated_payment: Option<common_utils::id_type::GlobalPaymentId>, + pub associated_token_id: Option<common_utils::id_type::GlobalTokenId>, } #[cfg(feature = "v2")] @@ -22,10 +26,12 @@ impl PaymentMethodSession { billing, psp_tokenization, network_tokenization, + tokenization_data, expires_at, return_url, associated_payment_methods, associated_payment, + associated_token_id, } = self; Self { @@ -34,10 +40,12 @@ impl PaymentMethodSession { billing: update_session.billing.or(billing), psp_tokenization: update_session.psp_tokenization.or(psp_tokenization), network_tokenization: update_session.network_tokenization.or(network_tokenization), + tokenization_data: update_session.tokenzation_data.or(tokenization_data), expires_at, return_url, associated_payment_methods, associated_payment, + associated_token_id, } } } @@ -47,4 +55,5 @@ pub struct PaymentMethodsSessionUpdateInternal { pub billing: Option<common_utils::encryption::Encryption>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + pub tokenzation_data: Option<masking::Secret<serde_json::Value>>, } diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index 9a886c473cd..7c8831b3811 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -39,6 +39,8 @@ pub mod relay; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; +#[cfg(feature = "tokenization_v2")] +pub mod tokenization; pub mod unified_translations; pub mod user; pub mod user_authentication_method; diff --git a/crates/diesel_models/src/query/tokenization.rs b/crates/diesel_models/src/query/tokenization.rs new file mode 100644 index 00000000000..0d818eb6636 --- /dev/null +++ b/crates/diesel_models/src/query/tokenization.rs @@ -0,0 +1,46 @@ +#[cfg(feature = "v2")] +use common_enums; +#[cfg(feature = "v2")] +use common_utils::{ + id_type::{GlobalTokenId, MerchantId}, + tokenization as tokenization_utils, +}; +#[cfg(feature = "v2")] +use diesel::{ + associations::HasTable, + deserialize::FromSqlRow, + expression::AsExpression, + pg::Pg, + serialize::{Output, ToSql}, + sql_types::{Jsonb, Text}, + AsChangeset, Identifiable, Insertable, Queryable, Selectable, +}; +#[cfg(feature = "v2")] +use serde::{Deserialize, Serialize}; +#[cfg(feature = "v2")] +use time::PrimitiveDateTime; + +#[cfg(feature = "v2")] +use crate::{ + query::generics, schema_v2::tokenization, tokenization as tokenization_diesel, PgPooledConn, + StorageResult, +}; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +impl tokenization_diesel::Tokenization { + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { + generics::generic_insert(conn, self).await + } + + pub async fn find_by_id( + conn: &PgPooledConn, + id: &common_utils::id_type::GlobalTokenId, + ) -> StorageResult<Self> { + use diesel::ExpressionMethods; + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + tokenization::dsl::id.eq(id.to_owned()), + ) + .await + } +} diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 195b0fa4298..b6d8aedfa92 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1379,6 +1379,26 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + tokenization (id) { + #[max_length = 64] + id -> Varchar, + #[max_length = 255] + merchant_id -> Varchar, + #[max_length = 64] + customer_id -> Varchar, + created_at -> Timestamp, + updated_at -> Timestamp, + #[max_length = 255] + locker_id -> Varchar, + flag -> TokenizationFlag, + version -> ApiVersion, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1532,6 +1552,7 @@ diesel::allow_tables_to_appear_in_same_query!( roles, routing_algorithm, themes, + tokenization, unified_translations, user_authentication_methods, user_key_store, diff --git a/crates/diesel_models/src/tokenization.rs b/crates/diesel_models/src/tokenization.rs new file mode 100644 index 00000000000..50a97e62c90 --- /dev/null +++ b/crates/diesel_models/src/tokenization.rs @@ -0,0 +1,61 @@ +#[cfg(feature = "v2")] +use common_enums; +#[cfg(feature = "v2")] +use common_utils::{ + id_type::{GlobalTokenId, MerchantId}, + tokenization as tokenization_utils, +}; +#[cfg(feature = "v2")] +use diesel::{ + associations::HasTable, + deserialize::FromSqlRow, + expression::AsExpression, + pg::Pg, + serialize::{Output, ToSql}, + sql_types::{Jsonb, Text}, + AsChangeset, Identifiable, Insertable, Queryable, Selectable, +}; +#[cfg(feature = "v2")] +use serde::{Deserialize, Serialize}; +#[cfg(feature = "v2")] +use time::PrimitiveDateTime; + +#[cfg(feature = "v2")] +use crate::{query::generics, schema_v2::tokenization, PgPooledConn, StorageResult}; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Clone, Debug, Identifiable, Insertable, Queryable)] +#[diesel(table_name = tokenization)] +pub struct Tokenization { + pub id: common_utils::id_type::GlobalTokenId, + pub merchant_id: common_utils::id_type::MerchantId, + pub customer_id: common_utils::id_type::GlobalCustomerId, + pub created_at: PrimitiveDateTime, + pub updated_at: PrimitiveDateTime, + pub locker_id: String, + pub flag: common_enums::enums::TokenizationFlag, + pub version: common_enums::enums::ApiVersion, +} + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Clone, Debug, Insertable)] +#[diesel(table_name = tokenization)] +pub struct TokenizationNew { + pub id: common_utils::id_type::GlobalTokenId, + pub merchant_id: common_utils::id_type::MerchantId, + pub customer_id: common_utils::id_type::GlobalCustomerId, + pub locker_id: String, + pub created_at: PrimitiveDateTime, + pub updated_at: PrimitiveDateTime, + pub version: common_enums::enums::ApiVersion, + pub flag: common_enums::enums::TokenizationFlag, +} + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Clone, Debug, AsChangeset)] +#[diesel(table_name = tokenization)] +pub struct TokenizationUpdate { + pub updated_at: Option<PrimitiveDateTime>, + pub version: Option<common_enums::enums::ApiVersion>, + pub flag: Option<common_enums::enums::TokenizationFlag>, +} diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index bf463616c6d..696cc22783d 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -9,6 +9,7 @@ use diesel::{ }; use masking::{Secret, WithType}; use serde::{self, Deserialize, Serialize}; + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, FromSqlRow, AsExpression)] #[diesel(sql_type = Jsonb)] pub struct OrderDetailsWithAmount { diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml index e889d2c16c3..a3a2fc8e10c 100644 --- a/crates/hyperswitch_domain_models/Cargo.toml +++ b/crates/hyperswitch_domain_models/Cargo.toml @@ -17,6 +17,7 @@ v2 = ["api_models/v2", "diesel_models/v2", "common_utils/v2", "common_types/v2"] v1 = ["api_models/v1", "diesel_models/v1", "common_utils/v1", "common_types/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2"] +tokenization_v2 = ["api_models/tokenization_v2", "diesel_models/tokenization_v2"] refunds_v2 = ["api_models/refunds_v2"] dummy_connector = [] revenue_recovery= [] diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index 1d24e3eedbc..eb37f8f45da 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -34,6 +34,8 @@ pub mod router_flow_types; pub mod router_request_types; pub mod router_response_types; pub mod routing; +#[cfg(feature = "tokenization_v2")] +pub mod tokenization; pub mod type_encryption; pub mod types; pub mod vault; diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs index c2be89a97e6..2f135ca881e 100644 --- a/crates/hyperswitch_domain_models/src/payment_methods.rs +++ b/crates/hyperswitch_domain_models/src/payment_methods.rs @@ -36,7 +36,11 @@ use crate::{ #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct VaultId(String); -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[cfg(any( + feature = "v2", + feature = "payment_methods_v2", + feature = "tokenization_v2" +))] impl VaultId { pub fn get_string_repr(&self) -> &String { &self.0 @@ -625,9 +629,11 @@ pub struct PaymentMethodSession { pub return_url: Option<common_utils::types::Url>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + pub tokenization_data: Option<pii::SecretSerdeValue>, pub expires_at: PrimitiveDateTime, pub associated_payment_methods: Option<Vec<id_type::GlobalPaymentMethodId>>, pub associated_payment: Option<id_type::GlobalPaymentId>, + pub associated_token_id: Option<id_type::GlobalTokenId>, } #[cfg(feature = "v2")] @@ -642,10 +648,12 @@ impl super::behaviour::Conversion for PaymentMethodSession { billing: self.billing.map(|val| val.into()), psp_tokenization: self.psp_tokenization, network_tokenization: self.network_tokenization, + tokenization_data: self.tokenization_data, expires_at: self.expires_at, associated_payment_methods: self.associated_payment_methods, associated_payment: self.associated_payment, return_url: self.return_url, + associated_token_id: self.associated_token_id, }) } @@ -694,10 +702,12 @@ impl super::behaviour::Conversion for PaymentMethodSession { billing, psp_tokenization: storage_model.psp_tokenization, network_tokenization: storage_model.network_tokenization, + tokenization_data: storage_model.tokenization_data, expires_at: storage_model.expires_at, associated_payment_methods: storage_model.associated_payment_methods, associated_payment: storage_model.associated_payment, return_url: storage_model.return_url, + associated_token_id: storage_model.associated_token_id, }) } .await @@ -713,10 +723,12 @@ impl super::behaviour::Conversion for PaymentMethodSession { billing: self.billing.map(|val| val.into()), psp_tokenization: self.psp_tokenization, network_tokenization: self.network_tokenization, + tokenization_data: self.tokenization_data, expires_at: self.expires_at, associated_payment_methods: self.associated_payment_methods, associated_payment: self.associated_payment, return_url: self.return_url, + associated_token_id: self.associated_token_id, }) } } @@ -878,6 +890,7 @@ pub enum PaymentMethodsSessionUpdateEnum { billing: Option<Encryptable<Address>>, psp_tokenization: Option<common_types::payment_methods::PspTokenization>, network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + tokenization_data: Option<pii::SecretSerdeValue>, }, } @@ -889,10 +902,12 @@ impl From<PaymentMethodsSessionUpdateEnum> for PaymentMethodsSessionUpdateIntern billing, psp_tokenization, network_tokenization, + tokenization_data, } => Self { billing, psp_tokenization, network_tokenization, + tokenization_data, }, } } @@ -907,10 +922,12 @@ impl PaymentMethodSession { billing, psp_tokenization, network_tokenization, + tokenization_data, expires_at, return_url, associated_payment_methods, associated_payment, + associated_token_id, } = self; Self { id, @@ -918,10 +935,12 @@ impl PaymentMethodSession { billing: update_session.billing.or(billing), psp_tokenization: update_session.psp_tokenization.or(psp_tokenization), network_tokenization: update_session.network_tokenization.or(network_tokenization), + tokenization_data: update_session.tokenization_data.or(tokenization_data), expires_at, return_url, associated_payment_methods, associated_payment, + associated_token_id, } } } @@ -931,6 +950,7 @@ pub struct PaymentMethodsSessionUpdateInternal { pub billing: Option<Encryptable<Address>>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, + pub tokenization_data: Option<pii::SecretSerdeValue>, } #[cfg(all( diff --git a/crates/hyperswitch_domain_models/src/tokenization.rs b/crates/hyperswitch_domain_models/src/tokenization.rs new file mode 100644 index 00000000000..4bbdaa2fb41 --- /dev/null +++ b/crates/hyperswitch_domain_models/src/tokenization.rs @@ -0,0 +1,105 @@ +use common_enums; +use common_utils::{ + self, + errors::{CustomResult, ValidationError}, + id_type, pii, + types::{keymanager, MinorUnit}, +}; +use diesel_models::tokenization; +use masking::{ExposeInterface, Secret}; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; + +use crate::{merchant_key_store::MerchantKeyStore, types}; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Tokenization { + pub id: common_utils::id_type::GlobalTokenId, + pub merchant_id: common_utils::id_type::MerchantId, + pub customer_id: common_utils::id_type::GlobalCustomerId, + pub locker_id: String, + pub created_at: PrimitiveDateTime, + pub updated_at: PrimitiveDateTime, + pub flag: common_enums::TokenizationFlag, + pub version: common_enums::ApiVersion, +} + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct TokenizationNew { + pub id: common_utils::id_type::GlobalTokenId, + pub merchant_id: common_utils::id_type::MerchantId, + pub customer_id: common_utils::id_type::GlobalCustomerId, + pub locker_id: String, + pub flag: common_enums::TokenizationFlag, + pub version: common_enums::ApiVersion, +} + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct TokenizationResponse { + pub token: String, + pub created_at: PrimitiveDateTime, + pub flag: common_enums::TokenizationFlag, +} + +impl From<Tokenization> for TokenizationResponse { + fn from(value: Tokenization) -> Self { + Self { + token: value.id.get_string_repr().to_string(), + created_at: value.created_at, + flag: value.flag, + } + } +} + +#[async_trait::async_trait] +impl super::behaviour::Conversion for Tokenization { + type DstType = diesel_models::tokenization::Tokenization; + type NewDstType = diesel_models::tokenization::Tokenization; + + async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + Ok(diesel_models::tokenization::Tokenization { + id: self.id, + merchant_id: self.merchant_id, + customer_id: self.customer_id, + locker_id: self.locker_id, + created_at: self.created_at, + updated_at: self.updated_at, + version: self.version, + flag: self.flag, + }) + } + + async fn convert_back( + _state: &keymanager::KeyManagerState, + item: Self::DstType, + _key: &Secret<Vec<u8>>, + _key_manager_identifier: keymanager::Identifier, + ) -> CustomResult<Self, ValidationError> { + Ok(Self { + id: item.id, + merchant_id: item.merchant_id, + customer_id: item.customer_id, + locker_id: item.locker_id, + created_at: item.created_at, + updated_at: item.updated_at, + flag: item.flag, + version: item.version, + }) + } + + async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + Ok(diesel_models::tokenization::Tokenization { + id: self.id, + merchant_id: self.merchant_id, + customer_id: self.customer_id, + locker_id: self.locker_id, + created_at: self.created_at, + updated_at: self.updated_at, + version: self.version, + flag: self.flag, + }) + } +} diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs index 49e9cbf54f7..35e55c8cb36 100644 --- a/crates/masking/src/lib.rs +++ b/crates/masking/src/lib.rs @@ -17,6 +17,8 @@ pub use abs::{ExposeInterface, ExposeOptionInterface, PeekInterface, SwitchStrat mod secret; mod strong_secret; +#[cfg(feature = "serde")] +pub use secret::JsonMaskStrategy; pub use secret::Secret; pub use strong_secret::StrongSecret; diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs index ee65b1c015b..f2f519dd3ed 100644 --- a/crates/masking/src/secret.rs +++ b/crates/masking/src/secret.rs @@ -167,3 +167,258 @@ impl AsRef<[u8]> for Secret<Vec<u8>> { self.peek().as_slice() } } + +/// Strategy for masking JSON values +#[cfg(feature = "serde")] +pub enum JsonMaskStrategy {} + +#[cfg(feature = "serde")] +impl Strategy<serde_json::Value> for JsonMaskStrategy { + fn fmt(value: &serde_json::Value, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match value { + serde_json::Value::Object(map) => { + write!(f, "{{")?; + let mut first = true; + for (key, val) in map { + if !first { + write!(f, ", ")?; + } + first = false; + write!(f, "\"{}\":", key)?; + Self::fmt(val, f)?; + } + write!(f, "}}") + } + serde_json::Value::Array(arr) => { + write!(f, "[")?; + let mut first = true; + for val in arr { + if !first { + write!(f, ", ")?; + } + first = false; + Self::fmt(val, f)?; + } + write!(f, "]") + } + serde_json::Value::String(s) => { + // For strings, we show a masked version that gives a hint about the content + let masked = if s.len() <= 2 { + "**".to_string() + } else if s.len() <= 6 { + format!("{}**", &s[0..1]) + } else { + // For longer strings, show first and last character with length in between + format!( + "{}**{}**{}", + &s[0..1], + s.len() - 2, + &s[s.len() - 1..s.len()] + ) + }; + write!(f, "\"{}\"", masked) + } + serde_json::Value::Number(n) => { + // For numbers, we can show the order of magnitude + if n.is_i64() || n.is_u64() { + let num_str = n.to_string(); + let masked_num = "*".repeat(num_str.len()); + write!(f, "{}", masked_num) + } else if n.is_f64() { + // For floats, just use a generic mask + write!(f, "**.**") + } else { + write!(f, "0") + } + } + serde_json::Value::Bool(b) => { + // For booleans, we can show a hint about which one it is + write!(f, "{}", if *b { "**true" } else { "**false" }) + } + serde_json::Value::Null => write!(f, "null"), + } + } +} + +#[cfg(test)] +#[cfg(feature = "serde")] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + #[allow(clippy::expect_used)] + fn test_json_mask_strategy() { + // Create a sample JSON with different types for testing + let original = json!({ "user": { "name": "John Doe", "email": "[email protected]", "age": 35, "verified": true }, "card": { "number": "4242424242424242", "cvv": 123, "amount": 99.99 }, "tags": ["personal", "premium"], "null_value": null, "short": "hi" }); + + // Apply the JsonMaskStrategy + let secret = Secret::<_, JsonMaskStrategy>::new(original.clone()); + let masked_str = format!("{:?}", secret); + + // Get specific values from original + let original_obj = original.as_object().expect("Original should be an object"); + let user_obj = original_obj["user"] + .as_object() + .expect("User should be an object"); + let name = user_obj["name"].as_str().expect("Name should be a string"); + let email = user_obj["email"] + .as_str() + .expect("Email should be a string"); + let age = user_obj["age"].as_i64().expect("Age should be a number"); + let verified = user_obj["verified"] + .as_bool() + .expect("Verified should be a boolean"); + + let card_obj = original_obj["card"] + .as_object() + .expect("Card should be an object"); + let card_number = card_obj["number"] + .as_str() + .expect("Card number should be a string"); + let cvv = card_obj["cvv"].as_i64().expect("CVV should be a number"); + + let tags = original_obj["tags"] + .as_array() + .expect("Tags should be an array"); + let tag1 = tags + .first() + .and_then(|v| v.as_str()) + .expect("First tag should be a string"); + + // Now explicitly verify the masking patterns for each value type + + // 1. String masking - pattern: first char + ** + length - 2 + ** + last char + let expected_name_mask = format!( + "\"{}**{}**{}\"", + &name[0..1], + name.len() - 2, + &name[name.len() - 1..] + ); + let expected_email_mask = format!( + "\"{}**{}**{}\"", + &email[0..1], + email.len() - 2, + &email[email.len() - 1..] + ); + let expected_card_mask = format!( + "\"{}**{}**{}\"", + &card_number[0..1], + card_number.len() - 2, + &card_number[card_number.len() - 1..] + ); + let expected_tag1_mask = if tag1.len() <= 2 { + "\"**\"".to_string() + } else if tag1.len() <= 6 { + format!("\"{}**\"", &tag1[0..1]) + } else { + format!( + "\"{}**{}**{}\"", + &tag1[0..1], + tag1.len() - 2, + &tag1[tag1.len() - 1..] + ) + }; + let expected_short_mask = "\"**\"".to_string(); // For "hi" + + // 2. Number masking + let expected_age_mask = "*".repeat(age.to_string().len()); // Repeat * for the number of digits + let expected_cvv_mask = "*".repeat(cvv.to_string().len()); + + // 3. Boolean masking + let expected_verified_mask = if verified { "**true" } else { "**false" }; + + // Check that the masked output includes the expected masked patterns + assert!( + masked_str.contains(&expected_name_mask), + "Name not masked correctly. Expected: {}", + expected_name_mask + ); + assert!( + masked_str.contains(&expected_email_mask), + "Email not masked correctly. Expected: {}", + expected_email_mask + ); + assert!( + masked_str.contains(&expected_card_mask), + "Card number not masked correctly. Expected: {}", + expected_card_mask + ); + assert!( + masked_str.contains(&expected_tag1_mask), + "Tag not masked correctly. Expected: {}", + expected_tag1_mask + ); + assert!( + masked_str.contains(&expected_short_mask), + "Short string not masked correctly. Expected: {}", + expected_short_mask + ); + + assert!( + masked_str.contains(&expected_age_mask), + "Age not masked correctly. Expected: {}", + expected_age_mask + ); + assert!( + masked_str.contains(&expected_cvv_mask), + "CVV not masked correctly. Expected: {}", + expected_cvv_mask + ); + + assert!( + masked_str.contains(expected_verified_mask), + "Boolean not masked correctly. Expected: {}", + expected_verified_mask + ); + + // Check structure preservation + assert!( + masked_str.contains("\"user\""), + "Structure not preserved - missing user object" + ); + assert!( + masked_str.contains("\"card\""), + "Structure not preserved - missing card object" + ); + assert!( + masked_str.contains("\"tags\""), + "Structure not preserved - missing tags array" + ); + assert!( + masked_str.contains("\"null_value\":null"), + "Null value not preserved correctly" + ); + + // Additional security checks to ensure no original values are exposed + assert!( + !masked_str.contains(name), + "Original name value exposed in masked output" + ); + assert!( + !masked_str.contains(email), + "Original email value exposed in masked output" + ); + assert!( + !masked_str.contains(card_number), + "Original card number exposed in masked output" + ); + assert!( + !masked_str.contains(&age.to_string()), + "Original age value exposed in masked output" + ); + assert!( + !masked_str.contains(&cvv.to_string()), + "Original CVV value exposed in masked output" + ); + assert!( + !masked_str.contains(tag1), + "Original tag value exposed in masked output" + ); + assert!( + !masked_str.contains("hi"), + "Original short string value exposed in masked output" + ); + } +} diff --git a/crates/openapi/Cargo.toml b/crates/openapi/Cargo.toml index 33c48e2f0ae..2fea584e9b1 100644 --- a/crates/openapi/Cargo.toml +++ b/crates/openapi/Cargo.toml @@ -17,7 +17,7 @@ common_types = { version = "0.1.0", path = "../common_types" } router_env = { version = "0.1.0", path = "../router_env" } [features] -v2 = ["api_models/v2", "api_models/customer_v2", "common_utils/v2", "api_models/payment_methods_v2", "common_utils/payment_methods_v2", "api_models/refunds_v2"] +v2 = ["api_models/v2", "api_models/customer_v2", "common_utils/v2", "api_models/payment_methods_v2", "common_utils/payment_methods_v2", "api_models/refunds_v2", "api_models/tokenization_v2"] v1 = ["api_models/v1", "common_utils/v1"] [lints] diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 9b8387389fe..45f8e87798a 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -157,6 +157,9 @@ Never share your secret api keys. Keep them guarded and secure. // Routes for proxy routes::proxy::proxy_core, + + // Route for tokenization + routes::tokenization::create_token_vault_api, ), components(schemas( common_utils::types::MinorUnit, @@ -736,6 +739,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::proxy::ProxyResponse, api_models::proxy::TokenType, routes::payments::ForceSync, + api_models::tokenization::GenericTokenizationRequest, + api_models::tokenization::GenericTokenizationResponse, )), modifiers(&SecurityAddon) )] diff --git a/crates/openapi/src/routes.rs b/crates/openapi/src/routes.rs index 8f95de75b3f..f2298c17ee5 100644 --- a/crates/openapi/src/routes.rs +++ b/crates/openapi/src/routes.rs @@ -20,4 +20,5 @@ pub mod refunds; pub mod relay; pub mod revenue_recovery; pub mod routing; +pub mod tokenization; pub mod webhook_events; diff --git a/crates/openapi/src/routes/tokenization.rs b/crates/openapi/src/routes/tokenization.rs new file mode 100644 index 00000000000..22f1227a9c0 --- /dev/null +++ b/crates/openapi/src/routes/tokenization.rs @@ -0,0 +1,33 @@ +use serde_json::json; +use utoipa::OpenApi; + +#[cfg(feature = "v2")] +#[utoipa::path( + post, + path = "/v2/tokenize", + request_body( + content = GenericTokenizationRequest, + examples(("Create a token with customer_id" = ( + value = json!({ + "customer_id": "12345_cus_0196d94b9c207333a297cbcf31f2e8c8", + "token_request": { + "payment_method_data": { + "card": { + "card_holder_name": "test name" + } + } + } + }) + ))) + ), + responses( + (status = 200, description = "Token created successfully", body = GenericTokenizationResponse), + (status = 400, description = "Invalid request"), + (status = 401, description = "Unauthorized"), + (status = 500, description = "Internal server error") + ), + tag = "Tokenization", + operation_id = "create_token_vault_api", + security(("ephemeral_key" = []),("api_key" = [])) +)] +pub async fn create_token_vault_api() {} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 06fd5ce67b1..9f6d807189d 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -33,13 +33,14 @@ payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors payout_retry = ["payouts"] recon = ["email", "api_models/recon"] retry = [] -v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","scheduler/v2", "refunds_v2", "euclid/v2", "payment_methods/v2"] +v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","scheduler/v2", "refunds_v2", "euclid/v2", "payment_methods/v2", "tokenization_v2"] v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1","scheduler/v1", "payment_methods/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"] revenue_recovery =["api_models/revenue_recovery","hyperswitch_interfaces/revenue_recovery","hyperswitch_domain_models/revenue_recovery","hyperswitch_connectors/revenue_recovery"] refunds_v2 = ["api_models/refunds_v2", "diesel_models/refunds_v2", "storage_impl/refunds_v2", "hyperswitch_domain_models/refunds_v2"] +tokenization_v2 = ["api_models/tokenization_v2", "diesel_models/tokenization_v2", "hyperswitch_domain_models/tokenization_v2", "storage_impl/tokenization_v2"] # Partial Auth # The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request. @@ -48,7 +49,7 @@ partial-auth = [] [dependencies] actix-cors = "0.6.5" -actix-http = "3.6.0" +actix-http = "3.6.0" actix-multipart = "0.6.1" actix-rt = "2.9.0" actix-web = "4.5.1" @@ -128,7 +129,7 @@ common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager", "encryption_service"] } common_types = { version = "0.1.0", path = "../common_types" } currency_conversion = { version = "0.1.0", path = "../currency_conversion" } -diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false } +diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store", "tokenization_v2"], default-features = false } euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] } events = { version = "0.1.0", path = "../events" } external_services = { version = "0.1.0", path = "../external_services" } diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index e67c3234b19..812d23165d5 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -67,3 +67,5 @@ pub mod proxy; pub mod relay; #[cfg(feature = "v2")] pub mod revenue_recovery; + +pub mod tokenization; diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 702b81f9720..8558b43491b 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -71,7 +71,7 @@ use crate::{ configs::settings, core::{ payment_methods::transformers as pm_transforms, payments as payments_core, - utils as core_utils, + tokenization as tokenization_core, utils as core_utils, }, db::errors::ConnectorErrorExt, headers, logger, @@ -2569,10 +2569,12 @@ pub async fn payment_methods_session_create( billing, psp_tokenization: request.psp_tokenization, network_tokenization: request.network_tokenization, + tokenization_data: request.tokenization_data, expires_at, return_url: request.return_url, associated_payment_methods: None, associated_payment: None, + associated_token_id: None, }; db.insert_payment_methods_session( @@ -2589,6 +2591,7 @@ pub async fn payment_methods_session_create( payment_method_session_domain_model, client_secret.secret, None, + None, ); Ok(services::ApplicationResponse::Json(response)) @@ -2638,6 +2641,7 @@ pub async fn payment_methods_session_update( billing, psp_tokenization: request.psp_tokenization, network_tokenization: request.network_tokenization, + tokenization_data: request.tokenization_data, }; let update_state_change = db @@ -2656,6 +2660,7 @@ pub async fn payment_methods_session_update( update_state_change, Secret::new("CLIENT_SECRET_REDACTED".to_string()), None, // TODO: send associated payments response based on the expandable param + None, ); Ok(services::ApplicationResponse::Json(response)) @@ -2685,6 +2690,7 @@ pub async fn payment_methods_session_retrieve( payment_method_session_domain_model, Secret::new("CLIENT_SECRET_REDACTED".to_string()), None, // TODO: send associated payments response based on the expandable param + None, ); Ok(services::ApplicationResponse::Json(response)) @@ -2873,6 +2879,8 @@ pub async fn payment_methods_session_confirm( }) .or_else(|| payment_method_session_billing.clone()); + let customer_id = payment_method_session.customer_id.clone(); + let create_payment_method_request = get_payment_method_create_request( request .payment_method_data @@ -2881,7 +2889,7 @@ pub async fn payment_methods_session_confirm( .get_required_value("payment_method_data")?, request.payment_method_type, request.payment_method_subtype, - payment_method_session.customer_id.clone(), + customer_id.clone(), unified_billing_address.as_ref(), Some(&payment_method_session), ) @@ -2936,11 +2944,35 @@ pub async fn payment_methods_session_confirm( None => None, }; + let tokenization_response = match payment_method_session.tokenization_data.clone() { + Some(tokenization_data) => { + let tokenization_response = tokenization_core::create_vault_token_core( + state.clone(), + &merchant_context.get_merchant_account().clone(), + &merchant_context.get_merchant_key_store().clone(), + api_models::tokenization::GenericTokenizationRequest { + customer_id: customer_id.clone(), + token_request: tokenization_data, + }, + ) + .await?; + let token = match tokenization_response { + services::ApplicationResponse::Json(response) => Some(response), + _ => None, + }; + Some(token) + } + None => None, + }; + + logger::debug!(?tokenization_response, "Tokenization response"); + //TODO: update the payment method session with the payment id and payment method id let payment_method_session_response = transformers::generate_payment_method_session_response( payment_method_session, Secret::new("CLIENT_SECRET_REDACTED".to_string()), payments_response, + (tokenization_response.flatten()), ); Ok(services::ApplicationResponse::Json( diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 31ecd45e466..fd36f6d0ab7 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -1021,6 +1021,7 @@ pub fn generate_payment_method_session_response( payment_method_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, client_secret: Secret<String>, associated_payment: Option<api_models::payments::PaymentsResponse>, + tokenization_service_response: Option<api_models::tokenization::GenericTokenizationResponse>, ) -> api_models::payment_methods::PaymentMethodSessionResponse { let next_action = associated_payment .as_ref() @@ -1034,6 +1035,10 @@ pub fn generate_payment_method_session_response( }, ); + let token_id = tokenization_service_response + .as_ref() + .map(|tokenization_service_response| tokenization_service_response.id.clone()); + api_models::payment_methods::PaymentMethodSessionResponse { id: payment_method_session.id, customer_id: payment_method_session.customer_id, @@ -1043,12 +1048,14 @@ pub fn generate_payment_method_session_response( .map(From::from), psp_tokenization: payment_method_session.psp_tokenization, network_tokenization: payment_method_session.network_tokenization, + tokenization_data: payment_method_session.tokenization_data, expires_at: payment_method_session.expires_at, client_secret, next_action, return_url: payment_method_session.return_url, associated_payment_methods: payment_method_session.associated_payment_methods, authentication_details, + associated_token_id: token_id, } } diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index e29527f9fe7..c545bcac503 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1355,6 +1355,30 @@ pub async fn retrieve_payment_method_from_vault_internal( Ok(stored_pm_resp) } +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[instrument(skip_all)] +pub async fn retrive_value_from_vault( + state: &routes::SessionState, + request: pm_types::VaultRetrieveRequest, +) -> CustomResult<serde_json::value::Value, errors::VaultError> { + let payload = request + .encode_to_vec() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode VaultRetrieveRequest")?; + + let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload) + .await + .change_context(errors::VaultError::VaultAPIError) + .attach_printable("Call to vault failed")?; + + let stored_resp: serde_json::Value = resp + .parse_struct("VaultRetrieveResponse") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Failed to parse data into VaultRetrieveResponse")?; + + Ok(stored_resp) +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault_external( diff --git a/crates/router/src/core/tokenization.rs b/crates/router/src/core/tokenization.rs new file mode 100644 index 00000000000..44bc53c77a0 --- /dev/null +++ b/crates/router/src/core/tokenization.rs @@ -0,0 +1,156 @@ +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use std::sync::Arc; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use actix_web::{web, HttpRequest, HttpResponse}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use api_models; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use common_enums::enums; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use common_utils::{ + crypto::{DecodeMessage, EncodeMessage, GcmAes256}, + errors::CustomResult, + ext_traits::{BytesExt, Encode, StringExt}, + id_type, +}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use error_stack::ResultExt; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use hyperswitch_domain_models; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use masking::{JsonMaskStrategy, Secret}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use router_env::{instrument, logger, tracing, Flow}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use serde::Serialize; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use crate::{ + core::{ + errors::{self, RouterResponse, RouterResult}, + payment_methods::vault as pm_vault, + tokenization, + }, + routes::{app::StorageInterface, AppState, SessionState}, + services::{self, api as api_service, authentication as auth}, + types::{api, domain, payment_methods as pm_types}, +}; + +#[instrument(skip_all)] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub async fn create_vault_token_core( + state: SessionState, + merchant_account: &domain::MerchantAccount, + merchant_key_store: &domain::MerchantKeyStore, + req: api_models::tokenization::GenericTokenizationRequest, +) -> RouterResponse<api_models::tokenization::GenericTokenizationResponse> { + // Generate a unique vault ID + let vault_id = domain::VaultId::generate(uuid::Uuid::now_v7().to_string()); + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + let customer_id = req.customer_id.clone(); + // Create vault request + let payload = pm_types::AddVaultRequest { + entity_id: merchant_account.get_id().to_owned(), + vault_id: vault_id.clone(), + data: req.token_request.clone(), + ttl: state.conf.locker.ttl_for_storage_in_secs, + } + .encode_to_vec() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode Request")?; + + // Call the vault service + let resp = pm_vault::call_to_vault::<pm_types::AddVault>(&state, payload.clone()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Call to vault failed")?; + + // Parse the response + let stored_resp: pm_types::AddVaultResponse = resp + .parse_struct("AddVaultResponse") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse data into AddVaultResponse")?; + + // Create new tokenization record + let tokenization_new = hyperswitch_domain_models::tokenization::Tokenization { + id: id_type::GlobalTokenId::generate(&state.conf.cell_information.id), + merchant_id: merchant_account.get_id().clone(), + customer_id: customer_id.clone(), + locker_id: stored_resp.vault_id.get_string_repr().to_string(), + created_at: common_utils::date_time::now(), + updated_at: common_utils::date_time::now(), + flag: enums::TokenizationFlag::Enabled, + version: enums::ApiVersion::V2, + }; + + // Insert into database + let tokenization = db + .insert_tokenization( + tokenization_new, + &(merchant_key_store.clone()), + key_manager_state, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to insert tokenization record")?; + + // Convert to TokenizationResponse + Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( + api_models::tokenization::GenericTokenizationResponse { + id: tokenization.id, + created_at: tokenization.created_at, + flag: tokenization.flag, + }, + )) +} + +#[instrument(skip_all)] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub async fn get_token_vault_core( + state: SessionState, + merchant_account: &domain::MerchantAccount, + merchant_key_store: &domain::MerchantKeyStore, + query: id_type::GlobalTokenId, +) -> CustomResult<serde_json::Value, errors::ApiErrorResponse> { + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + + let tokenization_record = db + .get_entity_id_vault_id_by_token_id( + &query, + &(merchant_key_store.clone()), + key_manager_state, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get tokenization record")?; + + if tokenization_record.flag == enums::TokenizationFlag::Disabled { + return Err(errors::ApiErrorResponse::GenericNotFoundError { + message: "Tokenization is disabled for the id".to_string(), + } + .into()); + } + + let vault_request = pm_types::VaultRetrieveRequest { + entity_id: tokenization_record.merchant_id.clone(), + vault_id: hyperswitch_domain_models::payment_methods::VaultId::generate( + tokenization_record.locker_id.clone(), + ), + }; + + let vault_data = pm_vault::retrive_value_from_vault(&state, vault_request) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve vault data")?; + + let data_json = vault_data + .get("data") + .cloned() + .unwrap_or(serde_json::Value::Null); + + // Create the response + Ok(data_json) +} diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 17938dbbe31..d77e1926260 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -61,7 +61,9 @@ use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; use masking::PeekInterface; use redis_interface::errors::RedisError; use router_env::logger; -use storage_impl::{errors::StorageError, redis::kv_store::RedisConnInterface, MockDb}; +use storage_impl::{ + errors::StorageError, redis::kv_store::RedisConnInterface, tokenization, MockDb, +}; pub use self::kafka_store::KafkaStore; use self::{fraud_check::FraudCheckInterface, organization::OrganizationInterface}; @@ -139,6 +141,7 @@ pub trait StorageInterface: + relay::RelayInterface + user::theme::ThemeInterface + payment_method_session::PaymentMethodsSessionInterface + + tokenization::TokenizationInterface + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 8c4ac07a32a..547846f8a0a 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -80,6 +80,7 @@ use crate::{ refund::RefundInterface, reverse_lookup::ReverseLookupInterface, routing_algorithm::RoutingAlgorithmInterface, + tokenization::TokenizationInterface, unified_translations::UnifiedTranslationsInterface, AccountsStorageInterface, CommonStorageInterface, GlobalStorageInterface, MasterKeyInterface, StorageInterface, @@ -87,7 +88,6 @@ use crate::{ services::{kafka::KafkaProducer, Store}, types::{domain, storage, AccessToken}, }; - #[derive(Debug, Clone, Serialize)] pub struct TenantID(pub String); @@ -4234,3 +4234,34 @@ impl CallbackMapperInterface for KafkaStore { self.diesel_store.find_call_back_mapper_by_id(id).await } } + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +#[async_trait::async_trait] +impl TokenizationInterface for KafkaStore { + async fn insert_tokenization( + &self, + tokenization: hyperswitch_domain_models::tokenization::Tokenization, + merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + self.diesel_store + .insert_tokenization(tokenization, merchant_key_store, key_manager_state) + .await + } + + async fn get_entity_id_vault_id_by_token_id( + &self, + token: &id_type::GlobalTokenId, + merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + self.diesel_store + .get_entity_id_vault_id_by_token_id(token, merchant_key_store, key_manager_state) + .await + } +} + +#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] +impl TokenizationInterface for KafkaStore {} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 0388f68225b..eb794a5c4fe 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -158,7 +158,10 @@ pub fn mk_app( .service(routes::PaymentMethodSession::server(state.clone())) .service(routes::Refunds::server(state.clone())); } - + #[cfg(all(feature = "v2", feature = "oltp", feature = "tokenization_v2"))] + { + server_app = server_app.service(routes::Tokenization::server(state.clone())); + } #[cfg(feature = "v1")] { server_app = server_app diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index f36e7b6049b..21db7a4624d 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -47,6 +47,7 @@ pub mod recon; pub mod refunds; #[cfg(feature = "olap")] pub mod routing; +pub mod tokenization; #[cfg(feature = "olap")] pub mod user; #[cfg(feature = "olap")] @@ -78,6 +79,8 @@ pub use self::app::PaymentMethodSession; pub use self::app::Proxy; #[cfg(all(feature = "olap", feature = "recon", feature = "v1"))] pub use self::app::Recon; +#[cfg(feature = "v2")] +pub use self::app::Tokenization; pub use self::app::{ ApiKeys, AppState, ApplePayCertificatesMigration, Cache, Cards, Configs, ConnectorOnboarding, Customers, Disputes, EphemeralKey, FeatureMatrix, Files, Forex, Gsm, Health, Hypersense, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 173ac34bd3a..6071a9ee0b0 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -55,6 +55,8 @@ use super::recovery_webhooks::*; use super::refunds; #[cfg(feature = "olap")] use super::routing; +#[cfg(all(feature = "oltp", feature = "v2"))] +use super::tokenization as tokenization_routes; #[cfg(all(feature = "olap", feature = "v1"))] use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains}; #[cfg(feature = "oltp")] @@ -1418,6 +1420,20 @@ impl PaymentMethodSession { } } +#[cfg(all(feature = "v2", feature = "oltp"))] +pub struct Tokenization; + +#[cfg(all(feature = "v2", feature = "oltp"))] +impl Tokenization { + pub fn server(state: AppState) -> Scope { + let mut token_route = web::scope("/v2/tokenize").app_data(web::Data::new(state)); + token_route = token_route.service( + web::resource("").route(web::post().to(tokenization_routes::create_token_vault_api)), + ); + token_route + } +} + #[cfg(all(feature = "olap", feature = "recon", feature = "v1"))] pub struct Recon; diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 1f224d2177c..8f14d5b5532 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -44,6 +44,7 @@ pub enum ApiIdentifier { PaymentMethodSession, ProcessTracker, Proxy, + GenericTokenization, } impl From<Flow> for ApiIdentifier { @@ -342,6 +343,8 @@ impl From<Flow> for ApiIdentifier { Flow::RevenueRecoveryRetrieve => Self::ProcessTracker, Flow::Proxy => Self::Proxy, + + Flow::TokenizationCreate | Flow::TokenizationRetrieve => Self::GenericTokenization, } } } diff --git a/crates/router/src/routes/tokenization.rs b/crates/router/src/routes/tokenization.rs new file mode 100644 index 00000000000..6becca19df7 --- /dev/null +++ b/crates/router/src/routes/tokenization.rs @@ -0,0 +1,74 @@ +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use std::sync::Arc; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use actix_web::{web, HttpRequest, HttpResponse}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use api_models; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use common_utils::{ + ext_traits::{BytesExt, Encode}, + id_type, +}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use error_stack::ResultExt; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use hyperswitch_domain_models; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use masking::Secret; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use router_env::{instrument, logger, tracing, Flow}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use serde::Serialize; + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use crate::{ + core::{ + api_locking, + errors::{self, RouterResult}, + tokenization, + }, + headers::X_CUSTOMER_ID, + routes::{app::StorageInterface, AppState, SessionState}, + services::{self, api as api_service, authentication as auth}, + types::{api, domain, payment_methods as pm_types}, +}; + +#[instrument(skip_all, fields(flow = ?Flow::TokenizationCreate))] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub async fn create_token_vault_api( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_models::tokenization::GenericTokenizationRequest>, +) -> HttpResponse { + let flow = Flow::TokenizationCreate; + let payload = json_payload.into_inner(); + let customer_id = payload.customer_id.clone(); + Box::pin(api_service::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationData, request, _| async move { + tokenization::create_vault_token_core( + state, + &auth.merchant_account, + &auth.key_store, + request, + ) + .await + }, + auth::api_or_client_auth( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Customer( + customer_id, + )), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs index 342347cd793..f05442ed45d 100644 --- a/crates/router/src/types/payment_methods.rs +++ b/crates/router/src/types/payment_methods.rs @@ -44,7 +44,11 @@ pub struct VaultFingerprintResponse { pub fingerprint_id: String, } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[cfg(any( + feature = "v2", + feature = "payment_methods_v2", + feature = "tokenization_v2" +))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultRequest<D> { pub entity_id: id_type::MerchantId, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 60a8939aeb0..c4fe30334b9 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -586,6 +586,10 @@ pub enum Flow { TotalPaymentMethodCount, /// Process Tracker Revenue Recovery Workflow Retrieve RevenueRecoveryRetrieve, + /// Tokenization flow + TokenizationCreate, + /// Tokenization retrieve flow + TokenizationRetrieve, /// Clone Connector flow CloneConnector, ///Proxy Flow diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml index ee849f78f46..4830201db74 100644 --- a/crates/storage_impl/Cargo.toml +++ b/crates/storage_impl/Cargo.toml @@ -18,6 +18,7 @@ v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "comm customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"] payment_methods_v2 = ["diesel_models/payment_methods_v2", "api_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2"] refunds_v2 = ["diesel_models/refunds_v2"] +tokenization_v2 = ["diesel_models/tokenization_v2", "api_models/tokenization_v2", "hyperswitch_domain_models/tokenization_v2"] [dependencies] # First Party dependencies diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 6cc5f035a7a..05fc865860a 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -32,6 +32,9 @@ pub mod utils; use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use database::store::PgPool; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use diesel_models::tokenization::Tokenization; +pub mod tokenization; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; pub use mock_db::MockDb; @@ -502,3 +505,14 @@ impl UniqueConstraints for diesel_models::Customer { impl<T: DatabaseStore> PayoutAttemptInterface for RouterStore<T> {} #[cfg(not(feature = "payouts"))] impl<T: DatabaseStore> PayoutsInterface for RouterStore<T> {} + +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +impl UniqueConstraints for diesel_models::tokenization::Tokenization { + fn unique_constraints(&self) -> Vec<String> { + vec![format!("id_{}", self.id.get_string_repr())] + } + + fn table_name(&self) -> &str { + "tokenization" + } +} diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index 1471f854de6..884d9747943 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -45,6 +45,8 @@ pub struct MockDb { pub mandates: Arc<Mutex<Vec<store::Mandate>>>, pub captures: Arc<Mutex<Vec<store::capture::Capture>>>, pub merchant_key_store: Arc<Mutex<Vec<store::merchant_key_store::MerchantKeyStore>>>, + #[cfg(all(feature = "v2", feature = "tokenization_v2"))] + pub tokenizations: Arc<Mutex<Vec<store::tokenization::Tokenization>>>, pub business_profiles: Arc<Mutex<Vec<store::business_profile::Profile>>>, pub reverse_lookups: Arc<Mutex<Vec<store::ReverseLookup>>>, pub payment_link: Arc<Mutex<Vec<store::payment_link::PaymentLink>>>, @@ -92,6 +94,8 @@ impl MockDb { mandates: Default::default(), captures: Default::default(), merchant_key_store: Default::default(), + #[cfg(all(feature = "v2", feature = "tokenization_v2"))] + tokenizations: Default::default(), business_profiles: Default::default(), reverse_lookups: Default::default(), payment_link: Default::default(), diff --git a/crates/storage_impl/src/tokenization.rs b/crates/storage_impl/src/tokenization.rs new file mode 100644 index 00000000000..5ecb6b0a813 --- /dev/null +++ b/crates/storage_impl/src/tokenization.rs @@ -0,0 +1,174 @@ +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use async_bb8_diesel::AsyncRunQueryDsl; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use common_utils::{ + errors::CustomResult, + ext_traits::OptionExt, + id_type::{CellId, GlobalTokenId, MerchantId}, + types::keymanager::KeyManagerState, +}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use diesel::{ExpressionMethods, Insertable, RunQueryDsl}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use diesel_models::{ + enums::TokenizationFlag as DbTokenizationFlag, + schema_v2::tokenization::dsl as tokenization_dsl, tokenization, PgPooledConn, +}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use error_stack::{report, Report, ResultExt}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use hyperswitch_domain_models::tokenization::Tokenization; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use hyperswitch_domain_models::{ + behaviour::{Conversion, ReverseConversion}, + merchant_key_store::MerchantKeyStore, +}; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use tokio::time; + +use super::MockDb; +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +use crate::{ + connection, diesel_error_to_data_error, errors, + kv_router_store::{ + FilterResourceParams, FindResourceBy, InsertResourceParams, UpdateResourceParams, + }, + redis::kv_store::{Op, PartitionKey}, + utils::{pg_connection_read, pg_connection_write}, +}; +use crate::{kv_router_store::KVRouterStore, DatabaseStore, RouterStore}; + +#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] +pub trait TokenizationInterface {} + +#[async_trait::async_trait] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +pub trait TokenizationInterface { + async fn insert_tokenization( + &self, + tokenization: hyperswitch_domain_models::tokenization::Tokenization, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; + + async fn get_entity_id_vault_id_by_token_id( + &self, + token: &common_utils::id_type::GlobalTokenId, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>; +} + +#[async_trait::async_trait] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +impl<T: DatabaseStore> TokenizationInterface for RouterStore<T> { + async fn insert_tokenization( + &self, + tokenization: hyperswitch_domain_models::tokenization::Tokenization, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + let conn = connection::pg_connection_write(self).await?; + + tokenization + .construct_new() + .await + .change_context(errors::StorageError::EncryptionError)? + .insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error)))? + .convert( + key_manager_state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError) + } + + async fn get_entity_id_vault_id_by_token_id( + &self, + token: &common_utils::id_type::GlobalTokenId, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + let conn = connection::pg_connection_read(self).await?; + + let tokenization = diesel_models::tokenization::Tokenization::find_by_id(&conn, token) + .await + .map_err(|error| report!(errors::StorageError::from(error)))?; + + let domain = tokenization + .convert( + key_manager_state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError)?; + + Ok(domain) + } +} + +#[async_trait::async_trait] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> { + async fn insert_tokenization( + &self, + tokenization: hyperswitch_domain_models::tokenization::Tokenization, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + self.router_store + .insert_tokenization(tokenization, merchant_key_store, key_manager_state) + .await + } + + async fn get_entity_id_vault_id_by_token_id( + &self, + token: &common_utils::id_type::GlobalTokenId, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + self.router_store + .get_entity_id_vault_id_by_token_id(token, merchant_key_store, key_manager_state) + .await + } +} + +#[async_trait::async_trait] +#[cfg(all(feature = "v2", feature = "tokenization_v2"))] +impl TokenizationInterface for MockDb { + async fn insert_tokenization( + &self, + tokenization: hyperswitch_domain_models::tokenization::Tokenization, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + Err(errors::StorageError::MockDbError)? + } + async fn get_entity_id_vault_id_by_token_id( + &self, + token: &common_utils::id_type::GlobalTokenId, + merchant_key_store: &MerchantKeyStore, + key_manager_state: &KeyManagerState, + ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> + { + Err(errors::StorageError::MockDbError)? + } +} + +#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] +impl TokenizationInterface for MockDb {} + +#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] +impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> {} + +#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] +impl<T: DatabaseStore> TokenizationInterface for RouterStore<T> {} diff --git a/v2_migrations/2025-04-25-105138_tokenization_service_creation/down.sql b/v2_migrations/2025-04-25-105138_tokenization_service_creation/down.sql new file mode 100644 index 00000000000..0eabe21fc74 --- /dev/null +++ b/v2_migrations/2025-04-25-105138_tokenization_service_creation/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +DROP TABLE IF EXISTS tokenization; +DROP TYPE "TokenizationFlag"; \ No newline at end of file diff --git a/v2_migrations/2025-04-25-105138_tokenization_service_creation/up.sql b/v2_migrations/2025-04-25-105138_tokenization_service_creation/up.sql new file mode 100644 index 00000000000..bfffd383ee5 --- /dev/null +++ b/v2_migrations/2025-04-25-105138_tokenization_service_creation/up.sql @@ -0,0 +1,13 @@ +-- Your SQL goes here +CREATE TYPE "TokenizationFlag" AS ENUM ('enabled', 'disabled'); + +CREATE TABLE IF NOT EXISTS tokenization ( + id VARCHAR(64) PRIMARY KEY, -- GlobalTokenId + merchant_id VARCHAR(255) NOT NULL, + customer_id VARCHAR(64) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + locker_id VARCHAR(255) NOT NULL, + flag "TokenizationFlag" NOT NULL DEFAULT 'enabled', + version "ApiVersion" NOT NULL DEFAULT 'v2' -- ApiVersion enum +); \ No newline at end of file
2025-04-25T11:46:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [x] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Create a new set of endpoints for giving tokenization as a service for generic usage, current motivation of the service is to be used in proxy payment service. ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **Create a token** ```bash curl --location 'http: //localhost:8080/v2/tokenize' \ --header 'x-profile-id: pro_neU1Qn8gnIich0LAaQXm' \ --header 'Authorization: publishable-key=PUBLISHABLE_KEY,client-secret=CLIENT_SECRET' \ --header 'Content-Type: application/json' \ --data '{ "customer_id": customer_id, "token_request": { "payment_method_data": { "card": { "card_holder_name": "Narayan Bhat" } } } }' ``` Response ```json { "id": "12345_tok_01966c6515157c3193db1c2502435ad5", "created_at": "2025-04-25 10:01:26.037519", "flag": "enabled" } ``` ## 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.114.0
8e9bad6457449ef2a435be03a9f97acc2dd2108a
8e9bad6457449ef2a435be03a9f97acc2dd2108a
juspay/hyperswitch
juspay__hyperswitch-7895
Bug: open router integration of elimination routing Add support for integrating open router's elimination routing in Hyperswitch
diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index c33365df169..07af605892f 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -10,14 +10,14 @@ pub use euclid::{ }; use serde::{Deserialize, Serialize}; -use crate::enums::{Currency, PaymentMethod, RoutableConnectors}; +use crate::enums::{Currency, PaymentMethod}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct OpenRouterDecideGatewayRequest { pub payment_info: PaymentInfo, pub merchant_id: id_type::ProfileId, - pub eligible_gateway_list: Option<Vec<RoutableConnectors>>, + pub eligible_gateway_list: Option<Vec<String>>, pub ranking_algorithm: Option<RankingAlgorithm>, pub elimination_enabled: Option<bool>, } @@ -80,7 +80,7 @@ pub struct UnifiedError { #[serde(rename_all = "camelCase")] pub struct UpdateScorePayload { pub merchant_id: id_type::ProfileId, - pub gateway: RoutableConnectors, + pub gateway: String, pub status: TxnStatus, pub payment_id: id_type::PaymentId, } @@ -91,7 +91,7 @@ pub enum TxnStatus { Started, AuthenticationFailed, JuspayDeclined, - PendingVBV, + PendingVbv, VBVSuccessful, Authorized, AuthorizationFailed, @@ -111,12 +111,3 @@ pub enum TxnStatus { Failure, Declined, } - -impl From<bool> for TxnStatus { - fn from(value: bool) -> Self { - match value { - true => Self::Charged, - _ => Self::Failure, - } - } -} diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index d3529edd29e..a683e3343aa 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -642,6 +642,17 @@ impl DynamicRoutingAlgorithmRef { pub fn update_volume_split(&mut self, volume: Option<u8>) { self.dynamic_routing_volume_split = volume } + + pub fn is_elimination_enabled(&self) -> bool { + self.elimination_routing_algorithm + .as_ref() + .map(|elimination_routing| { + elimination_routing.enabled_feature + == DynamicRoutingFeatures::DynamicConnectorSelection + || elimination_routing.enabled_feature == DynamicRoutingFeatures::Metrics + }) + .unwrap_or_default() + } } #[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)] diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 038751451ac..6bc55203615 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1516,6 +1516,7 @@ pub async fn perform_open_routing( profile.get_id().get_string_repr() ); + let is_elimination_enabled = dynamic_routing_algo_ref.is_elimination_enabled(); let connectors = dynamic_routing_algo_ref .success_based_algorithm .async_map(|algo| { @@ -1524,16 +1525,34 @@ pub async fn perform_open_routing( routable_connectors.clone(), profile.get_id(), algo, - payment_data, + &payment_data, + is_elimination_enabled, ) }) .await - .transpose() - .inspect_err(|e| logger::error!(dynamic_routing_error=?e)) - .ok() - .flatten() + .transpose()? .unwrap_or(routable_connectors); + if is_elimination_enabled { + // This will initiate the elimination process for the connector. + // Penalize the elimination score of the connector before making a payment. + // Once the payment is made, we will update the score based on the payment status + if let Some(connector) = connectors.first() { + logger::debug!( + "penalizing the elimination score of the gateway with id {} in open router for profile {}", + connector, profile.get_id().get_string_repr() + ); + update_success_rate_score_with_open_router( + state, + connector.clone(), + profile.get_id(), + &payment_data.payment_id, + common_enums::AttemptStatus::AuthenticationPending, + ) + .await? + } + } + Ok(connectors) } @@ -1634,7 +1653,8 @@ pub async fn perform_success_based_routing_with_open_router( mut routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile_id: &common_utils::id_type::ProfileId, success_based_algo_ref: api_routing::SuccessBasedAlgorithm, - payment_attempt: oss_storage::PaymentAttempt, + payment_attempt: &oss_storage::PaymentAttempt, + is_elimination_enabled: bool, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { if success_based_algo_ref.enabled_feature == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection @@ -1646,11 +1666,9 @@ pub async fn perform_success_based_routing_with_open_router( let open_router_req_body = OpenRouterDecideGatewayRequest::construct_sr_request( payment_attempt, - routable_connectors - .iter() - .map(|gateway| gateway.connector) - .collect::<Vec<_>>(), + routable_connectors.clone(), Some(or_types::RankingAlgorithm::SrBasedRouting), + is_elimination_enabled, ); let url = format!("{}/{}", &state.conf.open_router.url, "decide-gateway"); @@ -1724,15 +1742,15 @@ pub async fn perform_success_based_routing_with_open_router( #[instrument(skip_all)] pub async fn update_success_rate_score_with_open_router( state: &SessionState, - payment_connector: common_enums::RoutableConnectors, + payment_connector: api_routing::RoutableConnectorChoice, profile_id: &common_utils::id_type::ProfileId, payment_id: &common_utils::id_type::PaymentId, - payment_status: bool, + payment_status: common_enums::AttemptStatus, ) -> RoutingResult<()> { let open_router_req_body = or_types::UpdateScorePayload { merchant_id: profile_id.clone(), - gateway: payment_connector, - status: payment_status.into(), + gateway: payment_connector.to_string(), + status: payment_status.foreign_into(), payment_id: payment_id.clone(), }; @@ -1763,7 +1781,8 @@ pub async fn update_success_rate_score_with_open_router( )?; logger::debug!( - "Open router update_gateway_score response: {:?}", + "Open router update_gateway_score response for gateway with id {}: {:?}", + payment_connector, update_score_resp ); diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index b10500d2844..cf14c70ca32 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -8,6 +8,8 @@ use std::str::FromStr; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use std::sync::Arc; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use api_models::open_router; use api_models::routing as routing_types; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use common_utils::ext_traits::ValueExt; @@ -39,6 +41,8 @@ use storage_impl::redis::cache::Cacheable; use crate::db::errors::StorageErrorExt; #[cfg(feature = "v2")] use crate::types::domain::MerchantConnectorAccount; +#[cfg(all(feature = "dynamic_routing", feature = "v1"))] +use crate::types::transformers::ForeignFrom; use crate::{ core::errors::{self, RouterResult}, db::StorageInterface, @@ -729,20 +733,27 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( }, )?; - let payment_status_attribute = - get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status); + let routable_connector = routing_types::RoutableConnectorChoice { + choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, + connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to infer routable_connector from connector")?, + merchant_connector_id: payment_attempt.merchant_connector_id.clone(), + }; let should_route_to_open_router = state.conf.open_router.enabled; if should_route_to_open_router { + logger::debug!( + "performing update-gateway-score for gateway with id {} in open router for profile: {}", + routable_connector, profile_id.get_string_repr() + ); routing::payments_routing::update_success_rate_score_with_open_router( state, - common_enums::RoutableConnectors::from_str(payment_connector.as_str()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to infer routable_connector from connector")?, + routable_connector.clone(), profile_id, &payment_attempt.payment_id, - payment_status_attribute == common_enums::AttemptStatus::Charged, + payment_attempt.status, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -751,6 +762,9 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( return Ok(()); } + let payment_status_attribute = + get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status); + let success_based_routing_configs = fetch_dynamic_routing_configs::< routing_types::SuccessBasedRoutingConfig, >( @@ -972,17 +986,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( success_based_routing_configs, success_based_routing_config_params, vec![routing_types::RoutableConnectorChoiceWithStatus::new( - routing_types::RoutableConnectorChoice { - choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, - connector: common_enums::RoutableConnectors::from_str( - payment_connector.as_str(), - ) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "unable to infer routable_connector from connector", - )?, - merchant_connector_id: payment_attempt.merchant_connector_id.clone(), - }, + routable_connector, payment_status_attribute == common_enums::AttemptStatus::Charged, )], state.get_grpc_headers(), @@ -1350,6 +1354,38 @@ fn get_desired_payment_status_for_dynamic_routing_metrics( } } +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +impl ForeignFrom<common_enums::AttemptStatus> for open_router::TxnStatus { + fn foreign_from(attempt_status: common_enums::AttemptStatus) -> Self { + match attempt_status { + common_enums::AttemptStatus::Started => Self::Started, + common_enums::AttemptStatus::AuthenticationFailed => Self::AuthenticationFailed, + common_enums::AttemptStatus::RouterDeclined => Self::JuspayDeclined, + common_enums::AttemptStatus::AuthenticationPending => Self::PendingVbv, + common_enums::AttemptStatus::AuthenticationSuccessful => Self::VBVSuccessful, + common_enums::AttemptStatus::Authorized => Self::Authorized, + common_enums::AttemptStatus::AuthorizationFailed => Self::AuthorizationFailed, + common_enums::AttemptStatus::Charged => Self::Charged, + common_enums::AttemptStatus::Authorizing => Self::Authorizing, + common_enums::AttemptStatus::CodInitiated => Self::CODInitiated, + common_enums::AttemptStatus::Voided => Self::Voided, + common_enums::AttemptStatus::VoidInitiated => Self::VoidInitiated, + common_enums::AttemptStatus::CaptureInitiated => Self::CaptureInitiated, + common_enums::AttemptStatus::CaptureFailed => Self::CaptureFailed, + common_enums::AttemptStatus::VoidFailed => Self::VoidFailed, + common_enums::AttemptStatus::AutoRefunded => Self::AutoRefunded, + common_enums::AttemptStatus::PartialCharged => Self::PartialCharged, + common_enums::AttemptStatus::PartialChargedAndChargeable => Self::ToBeCharged, + common_enums::AttemptStatus::Unresolved => Self::Pending, + common_enums::AttemptStatus::Pending => Self::Pending, + common_enums::AttemptStatus::Failure => Self::Failure, + common_enums::AttemptStatus::PaymentMethodAwaited => Self::Pending, + common_enums::AttemptStatus::ConfirmationAwaited => Self::Pending, + common_enums::AttemptStatus::DeviceDataCollectionPending => Self::Pending, + } + } +} + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] fn get_dynamic_routing_based_metrics_outcome_for_payment( payment_status_attribute: common_enums::AttemptStatus, diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rs index d73e0d28671..85b6e5832a8 100644 --- a/crates/router/src/core/routing/transformers.rs +++ b/crates/router/src/core/routing/transformers.rs @@ -1,11 +1,12 @@ -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use api_models::open_router::{OpenRouterDecideGatewayRequest, PaymentInfo, RankingAlgorithm}; use api_models::routing::{ MerchantRoutingAlgorithm, RoutingAlgorithm as Algorithm, RoutingAlgorithmKind, RoutingDictionaryRecord, }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use common_enums::RoutableConnectors; +use api_models::{ + open_router::{OpenRouterDecideGatewayRequest, PaymentInfo, RankingAlgorithm}, + routing::RoutableConnectorChoice, +}; use common_utils::ext_traits::ValueExt; use diesel_models::{ enums as storage_enums, @@ -108,9 +109,10 @@ impl From<&routing::TransactionData<'_>> for storage_enums::TransactionType { #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub trait OpenRouterDecideGatewayRequestExt { fn construct_sr_request( - attempt: PaymentAttempt, - eligible_gateway_list: Vec<RoutableConnectors>, + attempt: &PaymentAttempt, + eligible_gateway_list: Vec<RoutableConnectorChoice>, ranking_algorithm: Option<RankingAlgorithm>, + is_elimination_enabled: bool, ) -> Self where Self: Sized; @@ -119,13 +121,14 @@ pub trait OpenRouterDecideGatewayRequestExt { #[cfg(all(feature = "v1", feature = "dynamic_routing"))] impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest { fn construct_sr_request( - attempt: PaymentAttempt, - eligible_gateway_list: Vec<RoutableConnectors>, + attempt: &PaymentAttempt, + eligible_gateway_list: Vec<RoutableConnectorChoice>, ranking_algorithm: Option<RankingAlgorithm>, + is_elimination_enabled: bool, ) -> Self { Self { payment_info: PaymentInfo { - payment_id: attempt.payment_id, + payment_id: attempt.payment_id.clone(), amount: attempt.net_amount.get_order_amount(), currency: attempt.currency.unwrap_or(storage_enums::Currency::USD), payment_type: "ORDER_PAYMENT".to_string(), @@ -133,10 +136,15 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest { payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt payment_method: attempt.payment_method.unwrap_or_default(), }, - merchant_id: attempt.profile_id, - eligible_gateway_list: Some(eligible_gateway_list), + merchant_id: attempt.profile_id.clone(), + eligible_gateway_list: Some( + eligible_gateway_list + .into_iter() + .map(|connector| connector.to_string()) + .collect(), + ), ranking_algorithm, - elimination_enabled: None, + elimination_enabled: Some(is_elimination_enabled), } } }
2025-04-24T13:31:59Z
## 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 the elimination routing integration support with open router. ### 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 merchant_account, api_key, mca 1. Enable elimination routing for merchant ``` curl --location --request POST 'http://localhost:8080/account/merchant_1744368166/business_profile/pro_GrzjTHd5Pn5hAhwTZPRn/dynamic_routing/elimination/toggle?enable=dynamic_connector_selection' \ --header 'api-key: xyz' ``` 2. Enable Volume split ``` curl --location --request POST 'http://localhost:8080/account/merchant_1744368166/business_profile/pro_GrzjTHd5Pn5hAhwTZPRn/dynamic_routing/set_volume_split?split=100' \ --header 'api-key: xyz' ``` 3. Create a Payment Search for the log " penalizing the elimination score of the gateway with id" ![image](https://github.com/user-attachments/assets/16bd41b3-5dd9-4911-b64e-4f53ceb50689) ## 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.113.0
bc7679d54f09c04037604c04e6a655ed5bf264cd
bc7679d54f09c04037604c04e6a655ed5bf264cd
juspay/hyperswitch
juspay__hyperswitch-7906
Bug: Fix: One click docker setup We need a script for one click docker setup
diff --git a/README.md b/README.md index 21b5d4def23..3033263e578 100644 --- a/README.md +++ b/README.md @@ -69,15 +69,27 @@ Read more at [Hyperswitch docs](https://docs.hyperswitch.io/). ### 1. Local Setup -You can run Hyperswitch on your system using Docker compose after cloning this repository. -We recommend using Docker Desktop (Or Orbstack) for Windows and Mac OS. On Linux, you can install Docker Engine directly. +#### One-Click Setup (Recommended) + +You can run Hyperswitch on your system with a single command using our one-click setup script: + ```shell git clone --depth 1 --branch latest https://github.com/juspay/hyperswitch cd hyperswitch -docker compose up -d -# This script verifies the setup and provides links to the individual components. -scripts/docker_output.sh +scripts/setup.sh ``` + +The above script will: +- Check for prerequisites (Docker Compose/Podman) +- Set up necessary configurations +- Let you select a deployment profile: + - **Standard**: Recommended - App server + Control Center + Web SDK. + - **Full**: Standard + Monitoring + Scheduler. + - **Standalone App Server**: Core services only (Hyperswitch server, PostgreSQL, Redis) +- Start the selected services +- Check service health +- Provide access information + The next step is to [configure a connector][configure-a-connector] with the Hyperswitch Control Center and [try a payment][try-a-payment]. Check out the [local setup guide][local-setup-guide] for more details on setting up the entire stack or component wise. diff --git a/docs/one_click_setup.md b/docs/one_click_setup.md new file mode 100644 index 00000000000..4eee5009360 --- /dev/null +++ b/docs/one_click_setup.md @@ -0,0 +1,97 @@ +# One-Click Docker Setup Guide + +This document provides detailed information about the one-click setup script for Hyperswitch. + +## Overview + +The `setup.sh` script simplifies the process of setting up Hyperswitch in a local development or testing environment. It provides an interactive setup experience that handles checking prerequisites, configuring the environment, and starting the necessary services. + +## Features + +- **Prerequisite Checking**: Verifies Docker/Podman and Docker/Podman Compose installation. +- **Port Availability Check**: Ensures required ports are available to avoid conflicts. +- **Configuration Management**: Automatically sets up necessary configuration files. +- **Multiple Deployment Profiles**: Choose the right setup for your needs. +- **Health Checking**: Verifies services are running and healthy. +- **Detailed Feedback**: Provides clear output and helpful error messages. + +## Deployment Profiles + +The script offers four deployment profiles to match your needs: + +### 1. Standard (Recommended) +- **Services**: App server + Control Center + Web SDK (includes PostgreSQL, Redis) +- **Best for**: General development and testing +- **Resources required**: Medium + +### 2. Full +- **Services**: Standard + Monitoring (Grafana, Prometheus) + Scheduler +- **Best for**: Complete system testing +- **Resources required**: Higher + +### 3. Standalone App Server +- **Services**: Hyperswitch server, PostgreSQL, Redis +- **Best for**: Testing basic API functionality +- **Resources required**: Lower + + +## Troubleshooting + +### Common Issues + +1. **Docker not running** + - **Error**: "Cannot connect to the Docker/Podman daemon" + - **Solution**: Start the Docker daemon/Docker Desktop or Use Orbstack. + +2. **Port conflicts** + - **Error**: "The following ports are already in use: [port list]" + - **Solution**: Stop services using those ports or choose different ports. + +3. **Server not becoming healthy** + - **Error**: "Hyperswitch server did not become healthy in the expected time." + - **Solution**: Check logs with `docker compose logs hyperswitch-server` or `podman compose logs hyperswitch-server`. + +### Viewing Logs + +To view logs for any service: +``` +docker compose logs -f [service-name] +``` + +Common service names: +- `hyperswitch-server` +- `pg` (PostgreSQL) +- `redis-standalone` +- `hyperswitch-control-center` + +## Advanced Usage + +### Environment Variables + +You can set these environment variables before running the script: + +- `DRAINER_INSTANCE_COUNT`: Number of drainer instances (default: 1) +- `REDIS_CLUSTER_COUNT`: Number of Redis cluster nodes (default: 3) + +Example: +``` +export DRAINER_INSTANCE_COUNT=2 +./setup.sh +``` + +### Manual Service Control + +After setup, you can manually control services: + +- Stop all services: `docker/podman compose down` +- Start specific services: `docker/podman compose up -d [service-name]` +- Restart a service: `docker/podman compose restart [service-name]` + +## Next Steps + +After running the setup script: + +1. Verify the server is running: `curl --head --request GET 'http://localhost:8080/health'`. +2. Access the Control Center at `http://localhost:9000`. +3. Configure payment connectors in the Control Center. +4. Try a test payment using the demo store. diff --git a/docs/try_local_system.md b/docs/try_local_system.md index 586e62acc7a..24ea5b9da6c 100644 --- a/docs/try_local_system.md +++ b/docs/try_local_system.md @@ -36,7 +36,7 @@ Check the Table Of Contents to jump to the relevant section. ## Run hyperswitch using Docker Compose -1. Install [Docker Compose][docker-compose-install]. +1. Install [Docker Compose][docker-compose-install] or [Podman Compose][podman-compose-install]. 2. Clone the repository and switch to the project directory: ```shell @@ -49,84 +49,15 @@ Check the Table Of Contents to jump to the relevant section. The provided configuration should work as is. If you do update the `docker_compose.toml` file, ensure to also update the corresponding values in the [`docker-compose.yml`][docker-compose-yml] file. -4. Start all the services using Docker Compose: +4. Start all the services using below script: ```shell - docker compose up -d - # This script verifies the setup and provides links to the individual components. - scripts/docker_output.sh - ``` - This should run the hyperswitch app server, web client and control center. - Wait for the `migration_runner` container to finish installing `diesel_cli` - and running migrations (approximately 2 minutes), and for the - `hyperswitch-web` container to finish compiling before proceeding further. - You can also choose to - [run the scheduler and monitoring services](#running-additional-services) - in addition to the app server, web client and control center. - -5. Verify that the server is up and running by hitting the health endpoint: - - ```shell - curl --head --request GET 'http://localhost:8080/health' + scripts/setup.sh ``` - - If the command returned a `200 OK` status code, proceed with - [trying out our APIs](#try-out-our-apis). - -### Running additional services - -The default behaviour for docker compose only runs the following services: - -1. postgres -2. redis (standalone) -3. hyperswitch server -4. hyperswitch control center -5. hyperswitch web sdk - -You can run the scheduler, data and monitoring services by specifying suitable profile -names to the above Docker Compose command. -To understand more about the hyperswitch architecture and the components -involved, check out the [architecture document][architecture]. - -- To run the scheduler components (consumer and producer), you can specify - `--profile scheduler`: - - ```shell - docker compose --profile scheduler up -d - ``` - -- To run the monitoring services (Grafana, Promtail, Loki, Prometheus and Tempo), - you can specify `--profile monitoring`: - - ```shell - docker compose --profile monitoring up -d - ``` - - You can then access Grafana at `http://localhost:3000` and view application - logs using the "Explore" tab, select Loki as the data source, and select the - container to query logs from. - -- To run the data services (Clickhouse, Kafka and Opensearch) you can specify the `olap` profile - - ```shell - docker compose --profile olap up -d - ``` - - You can read more about using the data services [here][data-docs] - -- You can also specify multiple profile names by specifying the `--profile` flag - multiple times. - To run both the scheduler components and monitoring services, the Docker - Compose command would be: - - ```shell - docker compose --profile scheduler --profile monitoring up -d - ``` - -Once the services have been confirmed to be up and running, you can proceed with -[trying out our APIs](#try-out-our-apis) + You will get prompts to select your preferred setup option. [docker-compose-install]: https://docs.docker.com/compose/install/ +[podman-compose-install]: https://podman.io/docs/installation [docker-compose-config]: /config/docker_compose.toml [docker-compose-yml]: /docker-compose.yml [architecture]: /docs/architecture.md diff --git a/scripts/setup.sh b/scripts/setup.sh new file mode 100755 index 00000000000..c40c5365c90 --- /dev/null +++ b/scripts/setup.sh @@ -0,0 +1,241 @@ +#! /usr/bin/env bash +set -euo pipefail + +# ANSI color codes for pretty output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +BLUE='\033[0;34m' +BOLD='\033[1m' +NC='\033[0m' # No Color + +# Alias for docker to use podman +alias docker=podman + +# Function to print colorful messages +echo_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +echo_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +echo_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +echo_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +show_banner() { + echo -e "${BLUE}${BOLD}" + echo "" + echo " # " + echo " # # # #### ##### ## # # " + echo " # # # # # # # # # # " + echo " # # # #### # # # # # " + echo " # # # # # ##### ###### # " + echo " # # # # # # # # # # " + echo " ##### #### #### # # # # " + echo "" + echo "" + echo " # # # # ##### ###### ##### #### # # # ##### #### # # " + echo " # # # # # # # # # # # # # # # # # # " + echo " # # # # # ##### # # #### # # # # # ###### " + echo " ####### # ##### # ##### # # ## # # # # # # " + echo " # # # # # # # # # ## ## # # # # # # " + echo " # # # # ###### # # #### # # # # #### # # " + echo "" + sleep 1 + echo -e "${NC}" + echo -e "🚀 ${BLUE}One-Click Docker Setup${NC} 🚀" + echo +} + +# Detect Docker Compose version +detect_docker_compose() { + # Check Docker or Podman + if command -v docker &> /dev/null; then + CONTAINER_ENGINE="docker" + echo_success "Docker is installed." + elif command -v podman &> /dev/null; then + CONTAINER_ENGINE="podman" + echo_success "Podman is installed." + else + echo_error "Neither Docker nor Podman is installed. Please install one of them to proceed." + echo_info "Visit https://docs.docker.com/get-docker/ or https://podman.io/docs/installation for installation instructions." + echo_info "After installation, re-run this script: scripts/setup.sh" + exit 1 + fi + + # Check Docker Compose or Podman Compose + if $CONTAINER_ENGINE compose version &> /dev/null; then + DOCKER_COMPOSE="$CONTAINER_ENGINE compose" + echo_success "Compose is installed for $CONTAINER_ENGINE." + else + echo_error "Compose is not installed for $CONTAINER_ENGINE. Please install $CONTAINER_ENGINE compose to proceed." + if [ "$CONTAINER_ENGINE" = "docker" ]; then + echo_info "Visit https://docs.docker.com/compose/install/ for installation instructions." + elif [ "$CONTAINER_ENGINE" = "podman" ]; then + echo_info "Visit https://podman-desktop.io/docs/compose/setting-up-compose for installation instructions." + fi + echo_info "After installation, re-run this script: scripts/setup.sh" + exit 1 + fi +} + +check_prerequisites() { + # Check curl + if ! command -v curl &> /dev/null; then + echo_error "curl is not installed. Please install curl to proceed." + exit 1 + fi + echo_success "curl is installed." + + # Check ports + required_ports=(8080 9000 9050 5432 6379 9060) + unavailable_ports=() + + for port in "${required_ports[@]}"; do + if command -v nc &> /dev/null; then + if nc -z localhost "$port" 2>/dev/null; then + unavailable_ports+=("$port") + fi + elif command -v lsof &> /dev/null; then + if lsof -i :"$port" &> /dev/null; then + unavailable_ports+=("$port") + fi + else + echo_warning "Neither nc nor lsof available to check ports. Skipping port check." + break + fi + done + + if [ ${#unavailable_ports[@]} -ne 0 ]; then + echo_warning "The following ports are already in use: ${unavailable_ports[*]}" + echo_warning "This might cause conflicts with Hyperswitch services." + read -p "Do you want to continue anyway? (y/n): " -n 1 -r + echo + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + exit 1 + fi + else + echo_success "All required ports are available." + fi +} + +setup_config() { + if [ ! -f "config/docker_compose.toml" ]; then + echo_error "Configuration file 'config/docker_compose.toml' not found. Please ensure the file exists and is correctly configured." + exit 1 + fi +} + +select_profile() { + echo "" + echo "Select a setup option:" + echo -e "1) Standard Setup: ${BLUE}[Recommended]${NC} Ideal for quick trial. Services included: ${BLUE}App Server, Control Center, Unified Checkout, PostgreSQL and Redis${NC}" + echo -e "2) Full Stack Setup: Ideal for comprehensive end-to-end payment testing. Services included: ${BLUE}Everything in Standard, Monitoring and Scheduler${NC}" + echo -e "3) Standalone App Server: Ideal for API-first integration testing. Services included: ${BLUE}App server, PostgreSQL and Redis)${NC}" + echo "" + local profile_selected=false + while [ "$profile_selected" = false ]; do + read -p "Enter your choice (1-3): " profile_choice + profile_choice=${profile_choice:-1} + + case $profile_choice in + 1) + PROFILE="standard" + profile_selected=true + ;; + 2) + PROFILE="full" + profile_selected=true + ;; + 3) + PROFILE="standalone" + profile_selected=true + ;; + *) + echo_error "Invalid choice. Please enter 1, 2, or 3." + ;; + esac + done + + echo "Selected setup: $PROFILE" +} + +start_services() { + + case $PROFILE in + standalone) + $DOCKER_COMPOSE up -d pg redis-standalone migration_runner hyperswitch-server + ;; + standard) + $DOCKER_COMPOSE up -d + ;; + full) + $DOCKER_COMPOSE --profile scheduler --profile monitoring --profile olap up -d + ;; + esac +} + +check_services_health() { + # Wait for the hyperswitch-server to be healthy + MAX_RETRIES=30 + RETRY_INTERVAL=5 + RETRIES=0 + + while [ $RETRIES -lt $MAX_RETRIES ]; do + if curl --silent --head --request GET 'http://localhost:8080/health' | grep "200 OK" > /dev/null; then + echo_success "Hyperswitch server is healthy!" + print_access_info # Call print_access_info only when the server is healthy + return + fi + + RETRIES=$((RETRIES+1)) + if [ $RETRIES -eq $MAX_RETRIES ]; then + echo "" + echo_error "${RED}${BOLD}Hyperswitch server did not become healthy in the expected time." + echo -e "Check logs with: $DOCKER_COMPOSE logs hyperswitch-server, Or reach out to us on slack(https://hyperswitch-io.slack.com/) for help." + echo -e "The setup process will continue, but some services might not work correctly.${NC}" + echo "" + else + echo "Waiting for server to become healthy... ($RETRIES/$MAX_RETRIES)" + sleep $RETRY_INTERVAL + fi + done +} + +print_access_info() { + echo "" + echo -e "${GREEN}${BOLD}Setup complete! You can access Hyperswitch services at:${NC}" + echo "" + + if [ "$PROFILE" != "standalone" ]; then + echo -e " • ${GREEN}${BOLD}Control Center${NC}: ${BLUE}${BOLD}http://localhost:9000${NC}" + fi + + echo -e " • ${GREEN}${BOLD}App Server${NC}: ${BLUE}${BOLD}http://localhost:8080${NC}" + + if [ "$PROFILE" != "standalone" ]; then + echo -e " • ${GREEN}${BOLD}Unified Checkout${NC}: ${BLUE}${BOLD}http://localhost:9060${NC}" + fi + + if [ "$PROFILE" = "full" ]; then + echo -e " • ${GREEN}${BOLD}Monitoring (Grafana)${NC}: ${BLUE}${BOLD}http://localhost:3000${NC}" + fi + echo "" + echo_info "To stop all services, run: $DOCKER_COMPOSE down" +} + +# Main execution flow +show_banner +detect_docker_compose +check_prerequisites +setup_config +select_profile +start_services +check_services_health # This will call print_access_info if the server is healthy
2025-04-12T12:17:12Z
Implements a comprehensive bash script that simplifies the Hyperswitch Docker setup process with the following features: - Prerequisites checking for Docker and Docker Compose - Port availability validation - Multiple deployment profiles (Minimal, Standard, Full, Development) - Automatic configuration setup - Service health monitoring - Detailed documentation in README.md and docs/one_click_setup.md Resolves issue #7761 ## 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 --> ### 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)? --> Sharing SS from local: <img width="635" alt="Screenshot 2025-04-24 at 5 59 43 AM" src="https://github.com/user-attachments/assets/2450115e-bb2d-4bc4-91ee-c53be713f9e2" /> ## 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.114.0
bbec7a41f7a088d6601195a2f4ce6d733924a443
bbec7a41f7a088d6601195a2f4ce6d733924a443
juspay/hyperswitch
juspay__hyperswitch-7891
Bug: Standardize Redis Key Prefix for User Lineage Context Currently, the lineage context is cached in Redis using tenant-specific key prefixes (public_, public_v2_). This causes inconsistencies across V1 and V2 environments — especially during login/logout flows — as lineage context data becomes deployment-specific. Need to introduce a new Redis connection helper that overrides the prefix with the global value from config (global).
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 3e339a2a570..13190125d7d 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -143,6 +143,27 @@ pub fn get_redis_connection(state: &SessionState) -> UserResult<Arc<RedisConnect .attach_printable("Failed to get redis connection") } +pub fn get_redis_connection_for_global_tenant( + state: &SessionState, +) -> UserResult<Arc<RedisConnectionPool>> { + let redis_connection_pool = state + .store + .get_redis_conn() + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get redis connection")?; + + let global_tenant_prefix = &state.conf.multitenancy.global_tenant.redis_key_prefix; + + Ok(Arc::new(RedisConnectionPool { + pool: Arc::clone(&redis_connection_pool.pool), + key_prefix: global_tenant_prefix.to_string(), + config: Arc::clone(&redis_connection_pool.config), + subscriber: Arc::clone(&redis_connection_pool.subscriber), + publisher: Arc::clone(&redis_connection_pool.publisher), + is_redis_available: Arc::clone(&redis_connection_pool.is_redis_available), + })) +} + impl ForeignFrom<&user_api::AuthConfig> for UserAuthType { fn foreign_from(from: &user_api::AuthConfig) -> Self { match *from { @@ -347,7 +368,7 @@ pub async fn get_lineage_context_from_cache( state: &SessionState, user_id: &str, ) -> UserResult<Option<LineageContext>> { - let connection = get_redis_connection(state)?; + let connection = get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); let lineage_context = connection .get_key::<Option<String>>(&key.into()) @@ -371,7 +392,7 @@ pub async fn set_lineage_context_in_cache( user_id: &str, lineage_context: LineageContext, ) -> UserResult<()> { - let connection = get_redis_connection(state)?; + let connection = get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); let serialized_lineage_context: String = serde_json::to_string(&lineage_context) .change_context(UserErrors::InternalServerError)
2025-04-24T12:20:59Z
## 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 updates the lineage context Redis caching logic to use a dedicated global Redis key prefix (`global`) instead of the default tenant-scoped prefixes (`public_`, `public_v2_`), causing inconsistencies between deployments (i.e., v1 and v2). Introduced a new helper: `get_redis_connection_for_global_tenant` - Fetches Redis connection with `key_prefix` set to `global`. - Updated lineage context caching (`get_lineage_context_from_cache`, `set_lineage_context_in_cache`) to use the global Redis connection This will enable [https://github.com/juspay/hyperswitch/pull/7871](https://github.com/juspay/hyperswitch/pull/7871) to work with both v1 and v2 merchant accounts. The redis-key should now be in the format of global:LINEAGE_CONTEXT_<user_id> ### 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). --> Previously, lineage context was being cached with environment-specific prefixes (`public_` in V1 and `public_v2_` in V2), leading to inconsistencies in user experience during login/logout flows across deployments. Switching to a consistent global prefix resolves this by isolating user lineage data under a unified Redis namespace. ## 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)? --> Use test cases from this PR: [https://github.com/juspay/hyperswitch/pull/7871](https://github.com/juspay/hyperswitch/pull/7871) The key should now be in the format of global:LINEAGE_CONTEXT_<user_id> <img width="1202" alt="image" src="https://github.com/user-attachments/assets/830883c3-5e08-4e00-b101-c2af6a251564" /> ## 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.113.0
54e910582fac9bd6fe300a9a96926adf5123403e
54e910582fac9bd6fe300a9a96926adf5123403e
juspay/hyperswitch
juspay__hyperswitch-7899
Bug: [FEATURE] Flowbird Archipel connector ### Feature Description Initial contribution from Flowbird. ### Possible Implementation Implementation of the Archipel connector. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
2025-04-18T10:19:58Z
[Flowbird Archipel connector implementation](https://www.flowbird.group/smartcity/us/wp-content/uploads/2019/11/Brochure-PAYMENT-ACCEPTANCE-EN-4-pages.pdf) Closes #7899 Co-authored-by: Guillaume Bague <[email protected]>
v1.114.0
1192bd5247dc099f647963a90ccc85a356b9f742
1192bd5247dc099f647963a90ccc85a356b9f742
juspay/hyperswitch
juspay__hyperswitch-7889
Bug: Add onboarding flow for VSAAS - Support for endpoint to create a platform - Create platform org and platform merchant account - Support to create connected merchant account inside platform org - Modify existing list responses for org and merchant, to distinguish platform from standard.
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 5e0564b4187..1a20e7b90b0 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -15,13 +15,13 @@ use crate::user::{ CreateTenantUserRequest, CreateUserAuthenticationMethodRequest, ForgotPasswordRequest, GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponseV2, InviteUserRequest, - ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, - SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest, - SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, - TwoFactorAuthStatusResponse, TwoFactorStatus, UpdateUserAccountDetailsRequest, - UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantAccountResponse, - UserMerchantCreate, UserOrgMerchantCreateRequest, VerifyEmailRequest, - VerifyRecoveryCodeRequest, VerifyTotpRequest, + PlatformAccountCreateRequest, PlatformAccountCreateResponse, ReInviteUserRequest, + RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, + SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest, SwitchMerchantRequest, + SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, TwoFactorAuthStatusResponse, + TwoFactorStatus, UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, + UserFromEmailRequest, UserMerchantAccountResponse, UserMerchantCreate, + UserOrgMerchantCreateRequest, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; common_utils::impl_api_event_type!( @@ -39,6 +39,8 @@ common_utils::impl_api_event_type!( SwitchProfileRequest, CreateInternalUserRequest, CreateTenantUserRequest, + PlatformAccountCreateRequest, + PlatformAccountCreateResponse, UserOrgMerchantCreateRequest, UserMerchantAccountResponse, UserMerchantCreate, diff --git a/crates/api_models/src/organization.rs b/crates/api_models/src/organization.rs index c6bc3924d11..e7ec5d32d74 100644 --- a/crates/api_models/src/organization.rs +++ b/crates/api_models/src/organization.rs @@ -1,14 +1,17 @@ +use common_enums::OrganizationType; use common_utils::{id_type, pii}; use utoipa::ToSchema; pub struct OrganizationNew { pub org_id: id_type::OrganizationId, + pub org_type: OrganizationType, pub org_name: Option<String>, } impl OrganizationNew { - pub fn new(org_name: Option<String>) -> Self { + pub fn new(org_type: OrganizationType, org_name: Option<String>) -> Self { Self { org_id: id_type::OrganizationId::default(), + org_type, org_name, } } @@ -47,6 +50,9 @@ pub struct OrganizationUpdateRequest { /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, + + /// Platform merchant id is unique distiguisher for special merchant in the platform org + pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index aa39877f0c7..d979a2d5a11 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -130,6 +130,20 @@ pub struct UserOrgMerchantCreateRequest { pub merchant_name: Secret<String>, } +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct PlatformAccountCreateRequest { + pub organization_name: Secret<String>, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct PlatformAccountCreateResponse { + pub org_id: id_type::OrganizationId, + pub org_name: Option<String>, + pub org_type: common_enums::OrganizationType, + pub merchant_id: id_type::MerchantId, + pub merchant_account_type: common_enums::MerchantAccountType, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserMerchantCreate { pub company_name: String, @@ -381,6 +395,7 @@ pub struct UserTransferKeyResponse { pub struct ListOrgsForUserResponse { pub org_id: id_type::OrganizationId, pub org_name: Option<String>, + pub org_type: common_enums::OrganizationType, } #[derive(Debug, serde::Serialize)] @@ -388,6 +403,7 @@ pub struct UserMerchantAccountResponse { pub merchant_id: id_type::MerchantId, pub merchant_name: OptionalEncryptableName, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, pub version: common_enums::ApiVersion, } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 2643b97904c..01abaf277f0 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -6,7 +6,7 @@ use std::{ num::{ParseFloatError, TryFromIntError}, }; -pub use accounts::MerchantProductType; +pub use accounts::{MerchantAccountType, MerchantProductType, OrganizationType}; pub use payments::ProductType; use serde::{Deserialize, Serialize}; pub use ui::*; diff --git a/crates/common_enums/src/enums/accounts.rs b/crates/common_enums/src/enums/accounts.rs index e5b3ef733c6..7500dcac7c8 100644 --- a/crates/common_enums/src/enums/accounts.rs +++ b/crates/common_enums/src/enums/accounts.rs @@ -26,3 +26,46 @@ pub enum MerchantProductType { CostObservability, DynamicRouting, } + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum MerchantAccountType { + #[default] + Standard, + Platform, + Connected, +} + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum OrganizationType { + #[default] + Standard, + Platform, +} diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs index 40c6a1e4ff3..e0b421f40c9 100644 --- a/crates/diesel_models/src/merchant_account.rs +++ b/crates/diesel_models/src/merchant_account.rs @@ -54,6 +54,7 @@ pub struct MerchantAccount { pub is_platform_account: bool, pub id: Option<common_utils::id_type::MerchantId>, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: Option<common_enums::MerchantAccountType>, } #[cfg(feature = "v1")] @@ -88,6 +89,7 @@ pub struct MerchantAccountSetter { pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v1")] @@ -125,6 +127,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, + merchant_account_type: Some(item.merchant_account_type), } } } @@ -158,6 +161,7 @@ pub struct MerchantAccount { pub is_platform_account: bool, pub id: common_utils::id_type::MerchantId, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: Option<common_enums::MerchantAccountType>, } #[cfg(feature = "v2")] @@ -177,6 +181,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, + merchant_account_type: Some(item.merchant_account_type), } } } @@ -196,6 +201,7 @@ pub struct MerchantAccountSetter { pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } impl MerchantAccount { @@ -245,6 +251,7 @@ pub struct MerchantAccountNew { pub is_platform_account: bool, pub id: Option<common_utils::id_type::MerchantId>, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v2")] @@ -263,6 +270,7 @@ pub struct MerchantAccountNew { pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v2")] @@ -311,6 +319,7 @@ impl MerchantAccountUpdateInternal { id: source.id, is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), product_type: product_type.or(source.product_type), + merchant_account_type: source.merchant_account_type, } } } @@ -417,6 +426,7 @@ impl MerchantAccountUpdateInternal { is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), id: source.id, product_type: product_type.or(source.product_type), + merchant_account_type: source.merchant_account_type, } } } diff --git a/crates/diesel_models/src/organization.rs b/crates/diesel_models/src/organization.rs index 1ca86225934..ffa1e94fcfa 100644 --- a/crates/diesel_models/src/organization.rs +++ b/crates/diesel_models/src/organization.rs @@ -29,6 +29,8 @@ pub struct Organization { #[allow(dead_code)] organization_name: Option<String>, pub version: common_enums::ApiVersion, + pub organization_type: Option<common_enums::OrganizationType>, + pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] @@ -46,6 +48,8 @@ pub struct Organization { id: id_type::OrganizationId, organization_name: Option<String>, pub version: common_enums::ApiVersion, + pub organization_type: Option<common_enums::OrganizationType>, + pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v1")] @@ -61,6 +65,8 @@ impl Organization { id: _, organization_name: _, version, + organization_type, + platform_merchant_id, } = org_new; Self { id: Some(org_id.clone()), @@ -72,8 +78,14 @@ impl Organization { created_at, modified_at, version, + organization_type: Some(organization_type), + platform_merchant_id, } } + + pub fn get_organization_type(&self) -> common_enums::OrganizationType { + self.organization_type.unwrap_or_default() + } } #[cfg(feature = "v2")] @@ -87,6 +99,8 @@ impl Organization { created_at, modified_at, version, + organization_type, + platform_merchant_id, } = org_new; Self { id, @@ -96,8 +110,14 @@ impl Organization { created_at, modified_at, version, + organization_type: Some(organization_type), + platform_merchant_id, } } + + pub fn get_organization_type(&self) -> common_enums::OrganizationType { + self.organization_type.unwrap_or_default() + } } #[cfg(feature = "v1")] @@ -113,6 +133,8 @@ pub struct OrganizationNew { pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub version: common_enums::ApiVersion, + pub organization_type: common_enums::OrganizationType, + pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] @@ -126,11 +148,17 @@ pub struct OrganizationNew { pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub version: common_enums::ApiVersion, + pub organization_type: common_enums::OrganizationType, + pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v1")] impl OrganizationNew { - pub fn new(id: id_type::OrganizationId, organization_name: Option<String>) -> Self { + pub fn new( + id: id_type::OrganizationId, + organization_type: common_enums::OrganizationType, + organization_name: Option<String>, + ) -> Self { Self { org_id: id.clone(), org_name: organization_name.clone(), @@ -141,13 +169,19 @@ impl OrganizationNew { created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), version: common_types::consts::API_VERSION, + organization_type, + platform_merchant_id: None, } } } #[cfg(feature = "v2")] impl OrganizationNew { - pub fn new(id: id_type::OrganizationId, organization_name: Option<String>) -> Self { + pub fn new( + id: id_type::OrganizationId, + organization_type: common_enums::OrganizationType, + organization_name: Option<String>, + ) -> Self { Self { id, organization_name, @@ -156,6 +190,8 @@ impl OrganizationNew { created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), version: common_types::consts::API_VERSION, + organization_type, + platform_merchant_id: None, } } } @@ -169,6 +205,7 @@ pub struct OrganizationUpdateInternal { organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, modified_at: time::PrimitiveDateTime, + platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] @@ -179,6 +216,7 @@ pub struct OrganizationUpdateInternal { organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, modified_at: time::PrimitiveDateTime, + platform_merchant_id: Option<id_type::MerchantId>, } pub enum OrganizationUpdate { @@ -186,6 +224,7 @@ pub enum OrganizationUpdate { organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, + platform_merchant_id: Option<id_type::MerchantId>, }, } @@ -197,12 +236,14 @@ impl From<OrganizationUpdate> for OrganizationUpdateInternal { organization_name, organization_details, metadata, + platform_merchant_id, } => Self { org_name: organization_name.clone(), organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), + platform_merchant_id, }, } } @@ -216,11 +257,13 @@ impl From<OrganizationUpdate> for OrganizationUpdateInternal { organization_name, organization_details, metadata, + platform_merchant_id, } => Self { organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), + platform_merchant_id, }, } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index c25acc386f5..46a36bab8c9 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -750,6 +750,8 @@ diesel::table! { id -> Nullable<Varchar>, #[max_length = 64] product_type -> Nullable<Varchar>, + #[max_length = 64] + merchant_account_type -> Nullable<Varchar>, } } @@ -823,6 +825,10 @@ diesel::table! { id -> Nullable<Varchar>, organization_name -> Nullable<Text>, version -> ApiVersion, + #[max_length = 64] + organization_type -> Nullable<Varchar>, + #[max_length = 64] + platform_merchant_id -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 8f857a4db26..d9df67f0fb7 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -738,6 +738,8 @@ diesel::table! { id -> Varchar, #[max_length = 64] product_type -> Nullable<Varchar>, + #[max_length = 64] + merchant_account_type -> Nullable<Varchar>, } } @@ -800,6 +802,10 @@ diesel::table! { id -> Varchar, organization_name -> Nullable<Text>, version -> ApiVersion, + #[max_length = 64] + organization_type -> Nullable<Varchar>, + #[max_length = 64] + platform_merchant_id -> Nullable<Varchar>, } } diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index 8657af91c57..2cd1af98639 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -49,6 +49,7 @@ pub struct MerchantAccount { pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v1")] @@ -85,6 +86,7 @@ pub struct MerchantAccountSetter { pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v1")] @@ -121,6 +123,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, + merchant_account_type: item.merchant_account_type, } } } @@ -142,6 +145,7 @@ pub struct MerchantAccountSetter { pub is_platform_account: bool, pub version: common_enums::ApiVersion, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v2")] @@ -161,6 +165,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { is_platform_account, version, product_type, + merchant_account_type, } = item; Self { id, @@ -176,6 +181,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { is_platform_account, version, product_type, + merchant_account_type, } } } @@ -196,6 +202,7 @@ pub struct MerchantAccount { pub is_platform_account: bool, pub version: common_enums::ApiVersion, pub product_type: Option<common_enums::MerchantProductType>, + pub merchant_account_type: common_enums::MerchantAccountType, } impl MerchantAccount { @@ -575,6 +582,7 @@ impl super::behaviour::Conversion for MerchantAccount { version: common_types::consts::API_VERSION, is_platform_account: self.is_platform_account, product_type: self.product_type, + merchant_account_type: self.merchant_account_type, }; Ok(diesel_models::MerchantAccount::from(setter)) @@ -637,6 +645,7 @@ impl super::behaviour::Conversion for MerchantAccount { is_platform_account: item.is_platform_account, version: item.version, product_type: item.product_type, + merchant_account_type: item.merchant_account_type.unwrap_or_default(), }) } .await @@ -662,6 +671,7 @@ impl super::behaviour::Conversion for MerchantAccount { product_type: self .product_type .or(Some(common_enums::MerchantProductType::Orchestration)), + merchant_account_type: self.merchant_account_type, }) } } @@ -703,6 +713,7 @@ impl super::behaviour::Conversion for MerchantAccount { version: self.version, is_platform_account: self.is_platform_account, product_type: self.product_type, + merchant_account_type: self.merchant_account_type, }; Ok(diesel_models::MerchantAccount::from(setter)) @@ -782,6 +793,7 @@ impl super::behaviour::Conversion for MerchantAccount { version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, + merchant_account_type: item.merchant_account_type.unwrap_or_default(), }) } .await @@ -825,6 +837,7 @@ impl super::behaviour::Conversion for MerchantAccount { product_type: self .product_type .or(Some(common_enums::MerchantProductType::Orchestration)), + merchant_account_type: self.merchant_account_type, }) } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index a5c2fbd483f..7919af296d3 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -4,6 +4,7 @@ use api_models::{ admin::{self as admin_types}, enums as api_enums, routing as routing_types, }; +use common_enums::{MerchantAccountType, OrganizationType}; use common_utils::{ date_time, ext_traits::{AsyncExt, Encode, OptionExt, ValueExt}, @@ -142,6 +143,7 @@ pub async fn update_organization( organization_name: req.organization_name, organization_details: req.organization_details, metadata: req.metadata, + platform_merchant_id: req.platform_merchant_id, }; state .accounts_store @@ -336,6 +338,31 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { .create_or_validate(db) .await?; + let merchant_account_type = match organization.get_organization_type() { + OrganizationType::Standard => MerchantAccountType::Standard, + + OrganizationType::Platform => { + let accounts = state + .store + .list_merchant_accounts_by_organization_id( + &state.into(), + &organization.get_organization_id(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let platform_account_exists = accounts + .iter() + .any(|account| account.merchant_account_type == MerchantAccountType::Platform); + + if platform_account_exists { + MerchantAccountType::Connected + } else { + MerchantAccountType::Platform + } + } + }; + let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); @@ -405,6 +432,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { version: common_types::consts::API_VERSION, is_platform_account: false, product_type: self.product_type, + merchant_account_type, }, ) } @@ -461,7 +489,10 @@ impl CreateOrValidateOrganization { match self { #[cfg(feature = "v1")] Self::Create => { - let new_organization = api_models::organization::OrganizationNew::new(None); + let new_organization = api_models::organization::OrganizationNew::new( + OrganizationType::Standard, + None, + ); let db_organization = ForeignFrom::foreign_from(new_organization); db.insert_organization(db_organization) .await @@ -629,6 +660,18 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { .create_or_validate(db) .await?; + let merchant_account_type = match organization.get_organization_type() { + OrganizationType::Standard => MerchantAccountType::Standard, + // Blocking v2 merchant account create for platform + OrganizationType::Platform => { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Merchant account creation is not allowed for a platform organization" + .to_string(), + } + .into()) + } + }; + let key = key_store.key.into_inner(); let id = identifier.to_owned(); let key_manager_state = state.into(); @@ -675,6 +718,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { is_platform_account: false, version: common_types::consts::API_VERSION, product_type: self.product_type, + merchant_account_type, }), ) } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 6e5360d8848..ff90ca1dfac 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1497,6 +1497,71 @@ pub async fn create_tenant_user( Ok(ApplicationResponse::StatusOk) } +#[cfg(feature = "v1")] +pub async fn create_platform_account( + state: SessionState, + user_from_token: auth::UserFromToken, + req: user_api::PlatformAccountCreateRequest, +) -> UserResponse<user_api::PlatformAccountCreateResponse> { + let user_from_db = user_from_token.get_user_from_db(&state).await?; + + let new_merchant = domain::NewUserMerchant::try_from(req)?; + let new_organization = new_merchant.get_new_organization(); + let organization = new_organization.insert_org_in_db(state.clone()).await?; + + let merchant_account = new_merchant + .create_new_merchant_and_insert_in_db(state.to_owned()) + .await?; + + state + .accounts_store + .update_organization_by_org_id( + &organization.get_organization_id(), + diesel_models::organization::OrganizationUpdate::Update { + organization_name: None, + organization_details: None, + metadata: None, + platform_merchant_id: Some(merchant_account.get_id().to_owned()), + }, + ) + .await + .change_context(UserErrors::InternalServerError)?; + + let now = common_utils::date_time::now(); + + let user_role = domain::NewUserRole { + user_id: user_from_db.get_user_id().to_owned(), + role_id: common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(), + status: UserStatus::Active, + created_by: user_from_token.user_id.clone(), + last_modified_by: user_from_token.user_id.clone(), + created_at: now, + last_modified: now, + entity: domain::NoLevel, + }; + + user_role + .add_entity(domain::OrganizationLevel { + tenant_id: user_from_token + .tenant_id + .clone() + .unwrap_or(state.tenant.tenant_id.clone()), + org_id: merchant_account.organization_id.clone(), + }) + .insert_in_v2(&state) + .await?; + + Ok(ApplicationResponse::Json( + user_api::PlatformAccountCreateResponse { + org_id: organization.get_organization_id(), + org_name: organization.get_organization_name(), + org_type: organization.organization_type.unwrap_or_default(), + merchant_id: merchant_account.get_id().to_owned(), + merchant_account_type: merchant_account.merchant_account_type, + }, + )) +} + #[cfg(feature = "v1")] pub async fn create_org_merchant_for_user( state: SessionState, @@ -1537,6 +1602,7 @@ pub async fn create_merchant_account( merchant_id: domain_merchant_account.get_id().to_owned(), merchant_name: domain_merchant_account.merchant_name, product_type: domain_merchant_account.product_type, + merchant_account_type: domain_merchant_account.merchant_account_type, version: domain_merchant_account.version, }, )) @@ -2893,6 +2959,7 @@ pub async fn list_orgs_for_user( .map(|org| user_api::ListOrgsForUserResponse { org_id: org.get_organization_id(), org_name: org.get_organization_name(), + org_type: org.organization_type.unwrap_or_default(), }) .collect::<Vec<_>>(); @@ -2975,6 +3042,7 @@ pub async fn list_merchants_for_user_in_org( merchant_name: merchant_account.merchant_name.clone(), merchant_id: merchant_account.get_id().to_owned(), product_type: merchant_account.product_type, + merchant_account_type: merchant_account.merchant_account_type, version: merchant_account.version, }) .collect::<Vec<_>>(), diff --git a/crates/router/src/db/organization.rs b/crates/router/src/db/organization.rs index b1dc58f0402..bb4f125db2a 100644 --- a/crates/router/src/db/organization.rs +++ b/crates/router/src/db/organization.rs @@ -119,12 +119,14 @@ impl OrganizationInterface for super::MockDb { organization_name, organization_details, metadata, + platform_merchant_id, } => { organization_name .as_ref() .map(|org_name| org.set_organization_name(org_name.to_owned())); organization_details.clone_into(&mut org.organization_details); metadata.clone_into(&mut org.metadata); + platform_merchant_id.clone_into(&mut org.platform_merchant_id); org } }) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9dc67be1d2d..61d5e709420 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2183,6 +2183,7 @@ impl User { .service( web::resource("/tenant_signup").route(web::post().to(user::create_tenant_user)), ) + .service(web::resource("/create_platform").route(web::post().to(user::create_platform))) .service(web::resource("/create_org").route(web::post().to(user::user_org_create))) .service( web::resource("/create_merchant") diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 760a4bc890c..9e0642b4984 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -247,6 +247,7 @@ impl From<Flow> for ApiIdentifier { | Flow::SwitchOrg | Flow::SwitchMerchantV2 | Flow::SwitchProfile + | Flow::CreatePlatformAccount | Flow::UserOrgMerchantCreate | Flow::UserMerchantAccountCreate | Flow::GenerateSampleData diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index d075048ddb6..a6d9d75dc43 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -259,6 +259,29 @@ pub async fn create_tenant_user( .await } +#[cfg(feature = "v1")] +pub async fn create_platform( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::PlatformAccountCreateRequest>, +) -> HttpResponse { + let flow = Flow::CreatePlatformAccount; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, user: auth::UserFromToken, json_payload, _| { + user_core::create_platform_account(state, user, json_payload) + }, + &auth::JWTAuth { + permission: Permission::OrganizationAccountWrite, + }, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "v1")] pub async fn user_org_create( state: web::Data<AppState>, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 016995cb550..80dbb6d5258 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -23,7 +23,7 @@ use hyperswitch_domain_models::api::ApplicationResponse; use masking::{ExposeInterface, PeekInterface, Secret}; use once_cell::sync::Lazy; use rand::distributions::{Alphanumeric, DistString}; -use router_env::{env, logger}; +use router_env::logger; use time::PrimitiveDateTime; use unicode_segmentation::UnicodeSegmentation; #[cfg(feature = "keymanager_create")] @@ -267,9 +267,10 @@ impl NewUserOrganization { impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserOrganization { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> { - let new_organization = api_org::OrganizationNew::new(Some( - UserCompanyName::new(value.company_name)?.get_secret(), - )); + let new_organization = api_org::OrganizationNew::new( + common_enums::OrganizationType::Standard, + Some(UserCompanyName::new(value.company_name)?.get_secret()), + ); let db_organization = ForeignFrom::foreign_from(new_organization); Ok(Self(db_organization)) } @@ -277,7 +278,8 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserOrganization { impl From<user_api::SignUpRequest> for NewUserOrganization { fn from(_value: user_api::SignUpRequest) -> Self { - let new_organization = api_org::OrganizationNew::new(None); + let new_organization = + api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } @@ -285,7 +287,8 @@ impl From<user_api::SignUpRequest> for NewUserOrganization { impl From<user_api::ConnectAccountRequest> for NewUserOrganization { fn from(_value: user_api::ConnectAccountRequest) -> Self { - let new_organization = api_org::OrganizationNew::new(None); + let new_organization = + api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } @@ -297,6 +300,7 @@ impl From<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for Ne ) -> Self { let new_organization = api_org::OrganizationNew { org_id, + org_type: common_enums::OrganizationType::Standard, org_name: None, }; let db_organization = ForeignFrom::foreign_from(new_organization); @@ -308,15 +312,28 @@ impl From<UserMerchantCreateRequestWithToken> for NewUserOrganization { fn from(value: UserMerchantCreateRequestWithToken) -> Self { Self(diesel_org::OrganizationNew::new( value.2.org_id, + common_enums::OrganizationType::Standard, Some(value.1.company_name), )) } } +impl From<user_api::PlatformAccountCreateRequest> for NewUserOrganization { + fn from(value: user_api::PlatformAccountCreateRequest) -> Self { + let new_organization = api_org::OrganizationNew::new( + common_enums::OrganizationType::Platform, + Some(value.organization_name.expose()), + ); + let db_organization = ForeignFrom::foreign_from(new_organization); + Self(db_organization) + } +} + type InviteeUserRequestWithInvitedUserToken = (user_api::InviteUserRequest, UserFromToken); impl From<InviteeUserRequestWithInvitedUserToken> for NewUserOrganization { fn from(_value: InviteeUserRequestWithInvitedUserToken) -> Self { - let new_organization = api_org::OrganizationNew::new(None); + let new_organization = + api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } @@ -331,6 +348,7 @@ impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for Ne ) -> Self { let new_organization = api_org::OrganizationNew { org_id: merchant_account_identifier.org_id, + org_type: common_enums::OrganizationType::Standard, org_name: None, }; let db_organization = ForeignFrom::foreign_from(new_organization); @@ -349,7 +367,11 @@ impl ForeignFrom<api_models::user::UserOrgMerchantCreateRequest> metadata, .. } = item; - let mut org_new_db = Self::new(org_id, Some(organization_name.expose())); + let mut org_new_db = Self::new( + org_id, + common_enums::OrganizationType::Standard, + Some(organization_name.expose()), + ); org_new_db.organization_details = organization_details; org_new_db.metadata = metadata; org_new_db @@ -698,11 +720,8 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: UserMerchantCreateRequestWithToken) -> UserResult<Self> { - let merchant_id = if matches!(env::which(), env::Env::Production) { - id_type::MerchantId::try_from(MerchantId::new(value.1.company_name.clone())?)? - } else { - id_type::MerchantId::new_from_unix_timestamp() - }; + let merchant_id = + utils::user::generate_env_specific_merchant_id(value.1.company_name.clone())?; let (user_from_storage, user_merchant_create, user_from_token) = value; Ok(Self { merchant_id, @@ -719,6 +738,24 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant { } } +impl TryFrom<user_api::PlatformAccountCreateRequest> for NewUserMerchant { + type Error = error_stack::Report<UserErrors>; + + fn try_from(value: user_api::PlatformAccountCreateRequest) -> UserResult<Self> { + let merchant_id = utils::user::generate_env_specific_merchant_id( + value.organization_name.clone().expose(), + )?; + + let new_organization = NewUserOrganization::from(value); + Ok(Self { + company_name: None, + merchant_id, + new_organization, + product_type: Some(consts::user::DEFAULT_PRODUCT_TYPE), + }) + } +} + #[derive(Debug, Clone)] pub struct MerchantAccountIdentifier { pub merchant_id: id_type::MerchantId, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 187f0c864d3..fdf52240320 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1817,7 +1817,7 @@ impl ForeignFrom<api_models::organization::OrganizationNew> for diesel_models::organization::OrganizationNew { fn foreign_from(item: api_models::organization::OrganizationNew) -> Self { - Self::new(item.org_id, item.org_name) + Self::new(item.org_id, item.org_type, item.org_name) } } @@ -1825,13 +1825,17 @@ impl ForeignFrom<api_models::organization::OrganizationCreateRequest> for diesel_models::organization::OrganizationNew { fn foreign_from(item: api_models::organization::OrganizationCreateRequest) -> Self { - let org_new = api_models::organization::OrganizationNew::new(None); + // Create a new organization with a standard type by default + let org_new = api_models::organization::OrganizationNew::new( + common_enums::OrganizationType::Standard, + None, + ); let api_models::organization::OrganizationCreateRequest { organization_name, organization_details, metadata, } = item; - let mut org_new_db = Self::new(org_new.org_id, Some(organization_name)); + let mut org_new_db = Self::new(org_new.org_id, org_new.org_type, Some(organization_name)); org_new_db.organization_details = organization_details; org_new_db.metadata = metadata; org_new_db diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 13190125d7d..61fb8472f6d 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -312,11 +312,7 @@ pub fn create_merchant_account_request_for_org( org: organization::Organization, product_type: common_enums::MerchantProductType, ) -> UserResult<api_models::admin::MerchantAccountCreate> { - let merchant_id = if matches!(env::which(), env::Env::Production) { - id_type::MerchantId::try_from(domain::MerchantId::new(req.merchant_name.clone().expose())?)? - } else { - id_type::MerchantId::new_from_unix_timestamp() - }; + let merchant_id = generate_env_specific_merchant_id(req.merchant_name.clone().expose())?; let company_name = domain::UserCompanyName::new(req.merchant_name.expose())?; Ok(api_models::admin::MerchantAccountCreate { @@ -409,3 +405,12 @@ pub async fn set_lineage_context_in_cache( Ok(()) } + +pub fn generate_env_specific_merchant_id(value: String) -> UserResult<id_type::MerchantId> { + if matches!(env::which(), env::Env::Production) { + let raw_id = domain::MerchantId::new(value)?; + Ok(id_type::MerchantId::try_from(raw_id)?) + } else { + Ok(id_type::MerchantId::new_from_unix_timestamp()) + } +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 6a4ad4bcabe..abc115dc288 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -407,6 +407,8 @@ pub enum Flow { UpdateUserRole, /// Create merchant account for user in a org UserMerchantAccountCreate, + /// Create Platform + CreatePlatformAccount, /// Create Org in a given tenancy UserOrgMerchantCreate, /// Generate Sample Data diff --git a/migrations/2025-04-10-095823_add_platform_context_in_organization/down.sql b/migrations/2025-04-10-095823_add_platform_context_in_organization/down.sql new file mode 100644 index 00000000000..65379a80226 --- /dev/null +++ b/migrations/2025-04-10-095823_add_platform_context_in_organization/down.sql @@ -0,0 +1,6 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE organization DROP COLUMN IF EXISTS organization_type; +ALTER TABLE organization DROP COLUMN IF EXISTS platform_merchant_id; + +ALTER TABLE merchant_account DROP COLUMN IF EXISTS merchant_account_type; + diff --git a/migrations/2025-04-10-095823_add_platform_context_in_organization/up.sql b/migrations/2025-04-10-095823_add_platform_context_in_organization/up.sql new file mode 100644 index 00000000000..cbcabee8e06 --- /dev/null +++ b/migrations/2025-04-10-095823_add_platform_context_in_organization/up.sql @@ -0,0 +1,5 @@ +-- Your SQL goes here +ALTER TABLE organization ADD COLUMN IF NOT EXISTS organization_type VARCHAR(64); +ALTER TABLE organization ADD COLUMN IF NOT EXISTS platform_merchant_id VARCHAR(64); + +ALTER TABLE merchant_account ADD COLUMN IF NOT EXISTS merchant_account_type VARCHAR(64);
2025-04-23T22:40:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description The PR supports onboarding for new VSAAS merchants. - Creating Platform Org - Creation of Platform, and connected merchant accounts - Change List response of merchant and organization list. ### 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 Closes #7889 ## How did you test it? Following Flow: - Signup --> terminate 2FA --> List orgs/merchants --> create Merchant inside standard org --> List merchants/orgs to validate - CreatePlatform --> Swtich to Platform Org --> List merchants/orgs to validate --> Create Merchant inside platform org We can hit the following curls: **Signup** ``` curl --location 'http://localhost:8080/user/signup?token_only=true' \ --header 'x-tenant-id: test' \ --header 'Content-Type: application/json' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX3VwIiwicGF0aCI6W10sImV4cCI6MTc0NTY1ODA0MywidGVuYW50X2lkIjoicHVibGljIn0.1lHD7fOM64ZtP0rRaBnp5-oaC6vy411jMu-lsjHAyr0' \ --data-raw '{ "email": "[email protected]", "password": "Test@1234" }' ``` Response: ``` {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX3VwIiwicGF0aCI6W10sImV4cCI6MTc0NTY1ODA0MywidGVuYW50X2lkIjoicHVibGljIn0.1lHD7fOM64ZtP0rRaBnp5-oaC6vy411jMu-lsjHAyr0","token_type":"totp"} ``` **Terminate 2FA** ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX3VwIiwicGF0aCI6W10sImV4cCI6MTc0NTY1ODA0MywidGVuYW50X2lkIjoicHVibGljIn0.1lHD7fOM64ZtP0rRaBnp5-oaC6vy411jMu-lsjHAyr0' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' ``` Response ``` {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o","token_type":"user_info"} ``` **Create Merchant Account** ``` curl --location 'http://localhost:8080/user/create_merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' \ --data '{ "company_name": "in_standard" }' ``` Response: ``` {"merchant_id":"merchant_1745485331","merchant_name":"in_standard","product_type":"orchestration","merchant_account_type":"standard","version":"v1"} ``` **List Orgs** ``` curl --location 'http://localhost:8080/user/list/org' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDM2NzMyMTUtYWU3NS00NGMzLWJiYzEtMGY3YmMxYmYwMjdmIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzEyMjE0NDE5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcxMjM4NzMyOSwib3JnX2lkIjoib3JnXzhLb2lWNmhrcG9KSGZNcllER1ZhIn0.H2G9oGp_JBoz3k5S7fMvaaJ9T0cG5VtUjM0hU3ltM3g' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' ``` Response: ``` [{"org_id":"org_1TaQlxQhcvKA6JVFqHeh","org_name":null,"org_type":"standard"}] ``` **List Merchant** ``` curl --location 'http://localhost:8080/user/list/merchant' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDM2NzMyMTUtYWU3NS00NGMzLWJiYzEtMGY3YmMxYmYwMjdmIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzEyMjE0NDE5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcxMjM4NzMyOSwib3JnX2lkIjoib3JnXzhLb2lWNmhrcG9KSGZNcllER1ZhIn0.H2G9oGp_JBoz3k5S7fMvaaJ9T0cG5VtUjM0hU3ltM3g' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' ``` Response: ``` [{"merchant_id":"merchant_1745485242","merchant_name":null,"product_type":"orchestration","merchant_account_type":"standard","version":"v1"},{"merchant_id":"merchant_1745485331","merchant_name":"in_standard","product_type":"orchestration","merchant_account_type":"standard","version":"v1"}] ``` **Create Platform Org** ``` curl --location 'http://localhost:8080/user/create_platform' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' \ --data '{ "organization_name": "platform" }' ``` Response: status 200 OK, witth reponse containing platform details ``` {"org_id":"org_TgxsZW9EOXksNcMSeaUy","org_name":"platform","org_type":"platform","merchant_id":"merchant_1745575171","merchant_account_type":"platform"} ``` Switch Org ``` curl --location 'http://localhost:8080/user/switch/org' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1NDg3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODM5OSwib3JnX2lkIjoib3JnXzBFZXE4cU9ETVJGc3NiNGJXa0p5IiwicHJvZmlsZV9pZCI6InByb19QOGc0R0dhbk81dDFiUXczNVQ3aiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.UW9aqcLLXYi_3xOpLCB2vB2ecmMA7M4LHNXorPT0Odc' \ --data '{ "org_id": "org_0Eeq8qODMRFssb4bWkJy" }' ``` Resonse: ``` {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1NDg3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODM5OSwib3JnX2lkIjoib3JnXzBFZXE4cU9ETVJGc3NiNGJXa0p5IiwicHJvZmlsZV9pZCI6InByb19QOGc0R0dhbk81dDFiUXczNVQ3aiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.UW9aqcLLXYi_3xOpLCB2vB2ecmMA7M4LHNXorPT0Odc","token_type":"user_info"} ``` Create Merchant inside Platfrom ``` curl --location 'http://localhost:8080/user/create_merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1MjQyIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODA4MCwib3JnX2lkIjoib3JnXzFUYVFseFFoY3ZLQTZKVkZxSGVoIiwicHJvZmlsZV9pZCI6InByb19xbHhJbFRwZDkwVXZmNDJsVWRHZSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.cJSWGsE__epEWkuLKph8rBHJSvosq_-dfu2bR4dKb1o' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTY5ZmY1YWQtNjczMC00ZjRhLTg1MGEtYWY5MDU3OTgyMmYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ1NDg1NDg3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NTY1ODM5OSwib3JnX2lkIjoib3JnXzBFZXE4cU9ETVJGc3NiNGJXa0p5IiwicHJvZmlsZV9pZCI6InByb19QOGc0R0dhbk81dDFiUXczNVQ3aiIsInRlbmFudF9pZCI6InB1YmxpYyJ9.UW9aqcLLXYi_3xOpLCB2vB2ecmMA7M4LHNXorPT0Odc' \ --data '{ "company_name": "in_platform" }' ``` Response: ``` {"merchant_id":"merchant_1745485645","merchant_name":"in_platform","product_type":"orchestration","merchant_account_type":"connected","version":"v1"} ``` List Org Now the list orgs for user will give following response since there are two orgs ``` [{"org_id":"org_0Eeq8qODMRFssb4bWkJy","org_name":"platform","org_type":"platform"},{"org_id":"org_1TaQlxQhcvKA6JVFqHeh","org_name":null,"org_type":"standard"}] ``` List Merchant Inside platform there will be following merchants ``` [{"merchant_id":"merchant_1745485487","merchant_name":null,"product_type":"orchestration","merchant_account_type":"platform","version":"v1"},{"merchant_id":"merchant_1745485645","merchant_name":"in_platform","product_type":"orchestration","merchant_account_type":"connected","version":"v1"}] ``` ## 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.114.0
f70824ef5e56514e5fc40163dfed3a0fde29bd1f
f70824ef5e56514e5fc40163dfed3a0fde29bd1f
juspay/hyperswitch
juspay__hyperswitch-7883
Bug: [chore] add cardholder name to payment required fields Add cardholder name to payment required fields for Worldpay card payments.
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay.rs b/crates/hyperswitch_connectors/src/connectors/worldpay.rs index 4628eaf116e..645502b267d 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay.rs @@ -285,6 +285,7 @@ impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsRespons http_code: res.status_code, }, optional_correlation_id, + data.request.amount.unwrap_or(0), )) .change_context(errors::ConnectorError::ResponseHandlingFailed) } @@ -759,6 +760,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData http_code: res.status_code, }, optional_correlation_id, + data.request.amount, )) .change_context(errors::ConnectorError::ResponseHandlingFailed) } @@ -870,6 +872,7 @@ impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResp http_code: res.status_code, }, optional_correlation_id, + data.request.amount, )) .change_context(errors::ConnectorError::ResponseHandlingFailed) } diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs index 8fd41ea2031..adee7fb2891 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs @@ -86,34 +86,24 @@ fn fetch_payment_instrument( }, cvc: card.card_cvc, card_holder_name: billing_address.and_then(|address| address.get_optional_full_name()), - billing_address: if let Some(address) = - billing_address.and_then(|addr| addr.address.clone()) - { - Some(BillingAddress { - address1: address.line1.get_required_value("line1").change_context( - errors::ConnectorError::MissingRequiredField { - field_name: "line1", - }, - )?, - address2: address.line2, - address3: address.line3, - city: address.city.get_required_value("city").change_context( - errors::ConnectorError::MissingRequiredField { field_name: "city" }, - )?, - state: address.state, - postal_code: address.zip.get_required_value("zip").change_context( - errors::ConnectorError::MissingRequiredField { field_name: "zip" }, - )?, - country_code: address - .country - .get_required_value("country_code") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "country_code", - })?, - }) - } else { - None - }, + billing_address: billing_address + .and_then(|addr| addr.address.clone()) + .and_then(|address| { + match (address.line1, address.city, address.zip, address.country) { + (Some(address1), Some(city), Some(postal_code), Some(country_code)) => { + Some(BillingAddress { + address1, + address2: address.line2, + address3: address.line3, + city, + state: address.state, + postal_code, + country_code, + }) + } + _ => None, + } + }), })), PaymentMethodData::CardDetailsForNetworkTransactionId(raw_card_details) => { Ok(PaymentInstrument::RawCardForNTI(RawCardDetails { @@ -264,7 +254,7 @@ impl WorldpayPaymentsRequestData for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData> { fn get_return_url(&self) -> Result<String, error_stack::Report<errors::ConnectorError>> { - self.request.get_router_return_url() + self.request.get_complete_authorize_url() } fn get_auth_type(&self) -> &enums::AuthenticationType { @@ -681,6 +671,7 @@ impl<F, T> ForeignTryFrom<( ResponseRouterData<F, WorldpayPaymentsResponse, T, PaymentsResponseData>, Option<String>, + i64, )> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; @@ -688,9 +679,10 @@ impl<F, T> item: ( ResponseRouterData<F, WorldpayPaymentsResponse, T, PaymentsResponseData>, Option<String>, + i64, ), ) -> Result<Self, Self::Error> { - let (router_data, optional_correlation_id) = item; + let (router_data, optional_correlation_id, amount) = item; let (description, redirection_data, mandate_reference, network_txn_id, error) = router_data .response .other_fields @@ -770,7 +762,11 @@ impl<F, T> PaymentOutcome::FraudHighRisk => Some("Transaction marked as high risk".to_string()), _ => None, }; - let status = enums::AttemptStatus::from(worldpay_status.clone()); + let status = if amount == 0 && worldpay_status == PaymentOutcome::Authorized { + enums::AttemptStatus::Charged + } else { + enums::AttemptStatus::from(worldpay_status.clone()) + }; let response = match (optional_error_message, error) { (None, None) => Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::foreign_try_from(( diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 192d45c8fce..69cb4b97de4 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -1473,6 +1473,7 @@ fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { RequiredField::CardNumber, RequiredField::CardExpMonth, RequiredField::CardExpYear, + RequiredField::BillingUserFirstName, ], ), ),
2025-04-24T13:40:33Z
## 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 adds below changes - Add required field for Worldpay card transactions - card holder name. - Fix 3DS SetupMandate flows for Worldpay card transactions ### 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 Card holder name is a mandatory field which is required by WP during card transactions. Fixing the 3DS SetupMandate flow for Worldpay allows merchants to consume the functionality. ## How did you test it? <details> <summary>1. [No3DS] Create zero amount off_session payment</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_W87tjiH2egf7KXq7k4Z3Kr4b0DjNZKUqv7MgUxzaAaLa3RC2jREfBOzomE4DsAD7' \ --data-raw '{"amount":0,"currency":"SGD","confirm":true,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","setup_future_usage":"off_session","customer_id":"cus_GPjGfsYpA50dZpSocrbd","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4000000000002503","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"737"}},"metadata":{"Force-PSP":"Adyen","udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{}}},"session_expiry":60}' Response {"payment_id":"pay_wfFMLqmemSnqwZVHT3kM","merchant_id":"merchant_1745484169","status":"succeeded","amount":0,"net_amount":0,"shipping_cost":null,"amount_capturable":0,"amount_received":0,"connector":"worldpay","client_secret":"pay_wfFMLqmemSnqwZVHT3kM_secret_eeoF2tNW0wRyvp2pU3WP","created":"2025-04-24T13:31:24.448Z","currency":"SGD","customer_id":"cus_GPjGfsYpA50dZpSocrbd","customer":{"id":"cus_GPjGfsYpA50dZpSocrbd","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"no_three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_GPjGfsYpA50dZpSocrbd","created_at":1745501484,"expires":1745505084,"secret":"epk_a62a7064a7e34ccd8305d605ae359881"},"manual_retry_allowed":false,"connector_transaction_id":"23fbb1ff-43c0-4fc4-b27d-072e23683f97","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null},"feature_metadata":null,"reference_id":"23fbb1ff-43c0-4fc4-b27d-072e23683f97","payment_link":null,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_3YM2a6Tn1oMvHSLqrGSD","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-24T13:32:24.448Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_yg0qfrNde4WjKQH8Gi3h","payment_method_status":"active","updated":"2025-04-24T13:31:26.513Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"https://try.access.worldpay.com/tokens/eyJrIjoxLCJkIjoidFlEWFFxbDNSUDNZZDg4T0VoWVVxbkdlaFB0RUlvVjFQcEs5TU9KRk9TQT0ifQ","card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} </details> <details> <summary>2. [No3DS] Create non zero amount off_session payment</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_W87tjiH2egf7KXq7k4Z3Kr4b0DjNZKUqv7MgUxzaAaLa3RC2jREfBOzomE4DsAD7' \ --data-raw '{"amount":1000,"currency":"SGD","confirm":true,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","setup_future_usage":"off_session","customer_id":"cus_GPjGfsYpA50dZpSocrbd","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4000000000002503","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"737"}},"metadata":{"Force-PSP":"Adyen","udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{}}},"session_expiry":60}' Response {"payment_id":"pay_OmaRK9FIhoOR0opBCA5q","merchant_id":"merchant_1745484169","status":"succeeded","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":0,"amount_received":1000,"connector":"worldpay","client_secret":"pay_OmaRK9FIhoOR0opBCA5q_secret_BZ0tzOif151DIaYSqUWl","created":"2025-04-24T13:32:05.834Z","currency":"SGD","customer_id":"cus_GPjGfsYpA50dZpSocrbd","customer":{"id":"cus_GPjGfsYpA50dZpSocrbd","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"no_three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_GPjGfsYpA50dZpSocrbd","created_at":1745501525,"expires":1745505125,"secret":"epk_f3c123ca19364af294602e915a89a659"},"manual_retry_allowed":false,"connector_transaction_id":"eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNi4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99HBj426bdlJXCgTskLhNY5Ml0rXtEPNSyl2cbsnj4b2DZrMdENEzIjocoy3lSG96aYlW4Z+fnZKMutoUGX3m1:mDK4Giru8JHLS90mSN+Z+gkVKRI3EE1MXDv7dp+h3RhHFHGaPn9ksCvhYk:a:cH+e81VQ0:KjdVX14V+Q12mM8f8UUuVrb1pWfdmRX0ol0w4rW66yFNGsWi87tzkRENLR8ix3NBfHPU2KlzlyTrmR0mwasA4zRNlfY:bG7Aaa:GaUgn8jvCNhmdUlN6uDEfAu3+Gpx8cadeYO0VLI6Wl9In2xgejGQ0ri:BU5HlAn:UMGwtz7wDtU06VN+Rkfa60cHqFXxXOGsvxbfcVlSe:hmS+WwXVvDoxGmrxlJztOw0ZEV8g:Qgoe7iLzyfbMA1TfZNrYIkRNlWpYaVeOJiIYYCBgREKSZGhVAzktTueU3oo=","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null},"feature_metadata":null,"reference_id":"929b66d4-df1d-4660-a4a1-ec4c14136cea","payment_link":null,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_3YM2a6Tn1oMvHSLqrGSD","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-24T13:33:05.834Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_BMicZubaUj8L5mP3dk5M","payment_method_status":"active","updated":"2025-04-24T13:32:07.354Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"https://try.access.worldpay.com/tokens/eyJrIjoxLCJkIjoidFlEWFFxbDNSUDNZZDg4T0VoWVVxbkdlaFB0RUlvVjFQcEs5TU9KRk9TQT0ifQ","card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} </details> <details> <summary>3. [3DS] Create non zero amount off_session payment</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_W87tjiH2egf7KXq7k4Z3Kr4b0DjNZKUqv7MgUxzaAaLa3RC2jREfBOzomE4DsAD7' \ --data-raw '{"amount":1000,"currency":"SGD","confirm":true,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","setup_future_usage":"off_session","customer_id":"cus_GPjGfsYpA50dZpSocrbd","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4000000000002503","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"737"}},"metadata":{"Force-PSP":"Adyen","udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{}}},"session_expiry":60}' Response {"payment_id":"pay_V52ZUSmwZcawWT6SmhK9","merchant_id":"merchant_1745484169","status":"requires_customer_action","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":1000,"amount_received":null,"connector":"worldpay","client_secret":"pay_V52ZUSmwZcawWT6SmhK9_secret_xkcz8525E884zswbTF90","created":"2025-04-24T13:32:54.875Z","currency":"SGD","customer_id":"cus_GPjGfsYpA50dZpSocrbd","customer":{"id":"cus_GPjGfsYpA50dZpSocrbd","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_V52ZUSmwZcawWT6SmhK9/merchant_1745484169/pay_V52ZUSmwZcawWT6SmhK9_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_GPjGfsYpA50dZpSocrbd","created_at":1745501574,"expires":1745505174,"secret":"epk_79da3389a5d349a2a060f8ef6377ad7a"},"manual_retry_allowed":null,"connector_transaction_id":"eyJrIjoxLCJkIjoiZnFyaU40UENQRnQzVHRndEtDdDg0bHZkVGsyMlNGZkpHRmV3Q3UxRHVwSUxvQVZFYmcwR3Q5NHkrN0xNNitQMiJ9_2","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null},"feature_metadata":null,"reference_id":"0b390991-6688-40b9-8b95-950a65af5678","payment_link":null,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_3YM2a6Tn1oMvHSLqrGSD","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-24T13:33:54.875Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_1NL54rrmq8DE3vQ9VgZX","payment_method_status":"inactive","updated":"2025-04-24T13:32:55.282Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} Complete the payment by clicking the link cURL (retrieve) curl --location --request GET 'http://localhost:8080/payments/pay_V52ZUSmwZcawWT6SmhK9' \ --header 'Accept: application/json' \ --header 'api-key: dev_W87tjiH2egf7KXq7k4Z3Kr4b0DjNZKUqv7MgUxzaAaLa3RC2jREfBOzomE4DsAD7' Response {"payment_id":"pay_V52ZUSmwZcawWT6SmhK9","merchant_id":"merchant_1745484169","status":"succeeded","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":0,"amount_received":1000,"connector":"worldpay","client_secret":"pay_V52ZUSmwZcawWT6SmhK9_secret_xkcz8525E884zswbTF90","created":"2025-04-24T13:32:54.875Z","currency":"SGD","customer_id":"cus_GPjGfsYpA50dZpSocrbd","customer":{"id":"cus_GPjGfsYpA50dZpSocrbd","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNi4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99HBj426bdlJXCgTskLhNY5Ml0rXtEPNSyl2cbsnj4b2DZrMdENEzIjocoy3lSG96aYlW4Z+fnZKMutoUGX3m1:mmJTlkRKFQu2PsVe3y+vegKDX5ZP4XxijGSq2aIDDwI7FHGaPn9ksCvhYk:a:cH+e81VQ0:KjdVX14V+Q12mM8f8UUuVrb1pWfdmRX0ol0w4rW66yFNGsWi87tzkRENLR8ix3NBfHPU2KlzlyTrmR0mwasA4zRNlfY:bG7Aaa:GaUgn8jvCNhmdUlN6uDEfAu3+Gpx8cadeYO0VLI6Wl9IlLyMVREoNqKOzGKAWbV6MGEiI1GbjFu2YIwRaZQDXnodMGaowTzH8y6H4OLwV6Mey+WwXVvDoxGmrxlJztOw0ZEV8g:Qgoe7iLzyfbMA1TfZNrYIkRNlWpYaVeOJiIYYCBgREKSZGhVAzktTueU3oo=","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null},"feature_metadata":null,"reference_id":"69586da7-7ba1-4154-844c-35a4dddc9b86","payment_link":null,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_3YM2a6Tn1oMvHSLqrGSD","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-24T13:33:54.875Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_1NL54rrmq8DE3vQ9VgZX","payment_method_status":"active","updated":"2025-04-24T13:33:09.920Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} </details> <details> <summary>4. [3DS] Create zero amount off_session payment</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_W87tjiH2egf7KXq7k4Z3Kr4b0DjNZKUqv7MgUxzaAaLa3RC2jREfBOzomE4DsAD7' \ --data-raw '{"amount":0,"currency":"SGD","confirm":true,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","setup_future_usage":"off_session","customer_id":"cus_GPjGfsYpA50dZpSocrbd","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4000000000002503","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"737"}},"metadata":{"Force-PSP":"Adyen","udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{}}},"session_expiry":60}' Response {"payment_id":"pay_i87Xb0hGyY0UmG1yhrpH","merchant_id":"merchant_1745484169","status":"requires_customer_action","amount":0,"net_amount":0,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"worldpay","client_secret":"pay_i87Xb0hGyY0UmG1yhrpH_secret_sjCsGpNDs2T8YVZEjaid","created":"2025-04-24T13:35:09.354Z","currency":"SGD","customer_id":"cus_GPjGfsYpA50dZpSocrbd","customer":{"id":"cus_GPjGfsYpA50dZpSocrbd","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_i87Xb0hGyY0UmG1yhrpH/merchant_1745484169/pay_i87Xb0hGyY0UmG1yhrpH_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_GPjGfsYpA50dZpSocrbd","created_at":1745501709,"expires":1745505309,"secret":"epk_f1b950bdde6d4989a336c8322ef732a6"},"manual_retry_allowed":null,"connector_transaction_id":"eyJrIjoxLCJkIjoiY1d2OGxEdTVBbEF4M1VSNVIwK0FnTGpKakl1cVhVWWpZQ3laVHpxdm5WTUxvQVZFYmcwR3Q5NHkrN0xNNitQMiJ9_2","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null},"feature_metadata":null,"reference_id":"43da3943-2049-4e20-95fc-172a1b763dde","payment_link":null,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_3YM2a6Tn1oMvHSLqrGSD","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-24T13:36:09.354Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_Lih5KP2o2m4mcGBnlgWF","payment_method_status":"inactive","updated":"2025-04-24T13:35:10.457Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} cURL (retrieve) curl --location --request GET 'http://localhost:8080/payments/pay_i87Xb0hGyY0UmG1yhrpH' \ --header 'Accept: application/json' \ --header 'api-key: dev_W87tjiH2egf7KXq7k4Z3Kr4b0DjNZKUqv7MgUxzaAaLa3RC2jREfBOzomE4DsAD7' Response {"payment_id":"pay_i87Xb0hGyY0UmG1yhrpH","merchant_id":"merchant_1745484169","status":"succeeded","amount":0,"net_amount":0,"shipping_cost":null,"amount_capturable":0,"amount_received":0,"connector":"worldpay","client_secret":"pay_i87Xb0hGyY0UmG1yhrpH_secret_sjCsGpNDs2T8YVZEjaid","created":"2025-04-24T13:35:09.354Z","currency":"SGD","customer_id":"cus_GPjGfsYpA50dZpSocrbd","customer":{"id":"cus_GPjGfsYpA50dZpSocrbd","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"1142f6b3-364b-4988-a508-14b17c18b523","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null},"feature_metadata":null,"reference_id":"1142f6b3-364b-4988-a508-14b17c18b523","payment_link":null,"profile_id":"pro_5CNWfwHVvSY4jegnpzco","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_3YM2a6Tn1oMvHSLqrGSD","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-24T13:36:09.354Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_Lih5KP2o2m4mcGBnlgWF","payment_method_status":"active","updated":"2025-04-24T13:36:35.533Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} </details> ## 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.113.0
54e910582fac9bd6fe300a9a96926adf5123403e
54e910582fac9bd6fe300a9a96926adf5123403e
juspay/hyperswitch
juspay__hyperswitch-7886
Bug: [FIX] remove open-router configuration from docker compose toml
diff --git a/config/docker_compose.toml b/config/docker_compose.toml index d8f2d4bd34d..2f2f6843154 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -899,6 +899,3 @@ background_color = "#FFFFFF" [platform] enabled = true - -[open_router] -enabled = false
2025-04-24T04:27:28Z
## 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 removes the open-router configuration from docker_compose.toml ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Since this is just a docker config change and cypress was failing due to this, ensuring CI check pass for cypress should suffice ## 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.113.0
f966defb3bdb0cf8a0f55b23ba3e7eaa61af06db
f966defb3bdb0cf8a0f55b23ba3e7eaa61af06db
juspay/hyperswitch
juspay__hyperswitch-7878
Bug: Add support to create profile level custom role Closes issue : https://github.com/juspay/hyperswitch/issues/7740
diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs index ba63dd61a0c..67fb04099ce 100644 --- a/crates/diesel_models/src/role.rs +++ b/crates/diesel_models/src/role.rs @@ -9,7 +9,7 @@ use crate::{enums, schema::roles}; pub struct Role { pub role_name: String, pub role_id: String, - pub merchant_id: id_type::MerchantId, + pub merchant_id: Option<id_type::MerchantId>, pub org_id: id_type::OrganizationId, #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] pub groups: Vec<enums::PermissionGroup>, @@ -28,7 +28,7 @@ pub struct Role { pub struct RoleNew { pub role_name: String, pub role_id: String, - pub merchant_id: id_type::MerchantId, + pub merchant_id: Option<id_type::MerchantId>, pub org_id: id_type::OrganizationId, #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)] pub groups: Vec<enums::PermissionGroup>, diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 374b341a47e..c25acc386f5 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1361,7 +1361,7 @@ diesel::table! { #[max_length = 64] role_id -> Varchar, #[max_length = 64] - merchant_id -> Varchar, + merchant_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Varchar, groups -> Array<Nullable<Text>>, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 9a72f663e4f..8cc0dcf7ed6 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1289,7 +1289,7 @@ diesel::table! { #[max_length = 64] role_id -> Varchar, #[max_length = 64] - merchant_id -> Varchar, + merchant_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Varchar, groups -> Array<Nullable<Text>>, diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index 34f0e8187ca..9bb8be9cc6e 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -78,13 +78,6 @@ pub async fn create_role( return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("User trying to create org level custom role"); } - - // TODO: Remove in PR custom-role-write-pr - if matches!(role_entity_type, EntityType::Profile) { - return Err(report!(UserErrors::InvalidRoleOperation)) - .attach_printable("User trying to create profile level custom role"); - } - let requestor_entity_from_role_scope = EntityType::from(req.role_scope); if requestor_entity_from_role_scope < role_entity_type { @@ -120,13 +113,15 @@ pub async fn create_role( .await?; let (org_id, merchant_id, profile_id) = match role_entity_type { - EntityType::Organization | EntityType::Tenant => { - (user_from_token.org_id, user_from_token.merchant_id, None) - } - EntityType::Merchant => (user_from_token.org_id, user_from_token.merchant_id, None), + EntityType::Organization | EntityType::Tenant => (user_from_token.org_id, None, None), + EntityType::Merchant => ( + user_from_token.org_id, + Some(user_from_token.merchant_id), + None, + ), EntityType::Profile => ( user_from_token.org_id, - user_from_token.merchant_id, + Some(user_from_token.merchant_id), Some(user_from_token.profile_id), ), }; diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs index 532a59f5149..ecb962d8d29 100644 --- a/crates/router/src/db/role.rs +++ b/crates/router/src/db/role.rs @@ -265,7 +265,13 @@ impl RoleInterface for MockDb { && (role.tenant_id == *tenant_id) && role.org_id == *org_id && ((role.scope == RoleScope::Organization) - || (role.merchant_id == *merchant_id && role.scope == RoleScope::Merchant) + || (role + .merchant_id + .as_ref() + .is_some_and(|merchant_id_from_role| { + merchant_id_from_role == merchant_id + && role.scope == RoleScope::Merchant + })) || (role .profile_id .as_ref() @@ -369,10 +375,10 @@ impl RoleInterface for MockDb { let roles_list: Vec<_> = roles .iter() .filter(|role| { - let matches_merchant = match merchant_id { - Some(merchant_id) => role.merchant_id == *merchant_id, - None => true, - }; + let matches_merchant = merchant_id + .zip(role.merchant_id.as_ref()) + .map(|(merchant_id, role_merchant_id)| merchant_id == role_merchant_id) + .unwrap_or(true); matches_merchant && role.org_id == *org_id @@ -420,17 +426,26 @@ impl RoleInterface for MockDb { vec![EntityType::Merchant] }; + let matches_merchant = role + .merchant_id + .as_ref() + .is_some_and(|merchant_id_from_role| merchant_id_from_role == merchant_id); + role.tenant_id == tenant_id && role.org_id == org_id - && (role.scope == RoleScope::Organization - || role.merchant_id == *merchant_id) + && (role.scope == RoleScope::Organization || matches_merchant) && entity_in_vec.contains(&role.entity_type) } storage::ListRolesByEntityPayload::Profile(merchant_id, profile_id) => { let entity_in_vec = [EntityType::Profile]; let matches_merchant = - role.merchant_id == *merchant_id && role.scope == RoleScope::Merchant; + role.merchant_id + .as_ref() + .is_some_and(|merchant_id_from_role| { + merchant_id_from_role == merchant_id + && role.scope == RoleScope::Merchant + }); let matches_profile = role.profile_id diff --git a/migrations/2025-02-06-122415_udpate-roles/down.sql b/migrations/2025-02-06-122415_udpate-roles/down.sql new file mode 100644 index 00000000000..be66247abff --- /dev/null +++ b/migrations/2025-02-06-122415_udpate-roles/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE roles ALTER COLUMN merchant_id SET NOT NULL; \ No newline at end of file diff --git a/migrations/2025-02-06-122415_udpate-roles/up.sql b/migrations/2025-02-06-122415_udpate-roles/up.sql new file mode 100644 index 00000000000..490f5bcb929 --- /dev/null +++ b/migrations/2025-02-06-122415_udpate-roles/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE roles ALTER COLUMN merchant_id DROP NOT NULL; \ No newline at end of file
2025-04-23T07:32:46Z
## 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 will enable profile level custom creation from API and also enable org level custom role read ### Additional Changes - [ ] This PR modifies the API contract - [X] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1 . Valid operation Request : ``` curl --location 'http://localhost:8080/user/role' \ --header 'authorization: Bearer JWT' \ --header 'cookie: login_token=JWT' \ --data '{ "role_scope": "profile", "entity_type": "profile", "groups": [ "operations_view", "operations_manage" ], "role_name": "profile-role-at-profile-scope" }' ``` Response ``` { "role_id": "role_vcPMQVtjv0jblNi1tOxB", "groups": [ "operations_view", "operations_manage" ], "role_name": "profile-role-at-profile-scope", "role_scope": "profile", "entity_type": "profile" } ``` 2. Invalid operation Request ``` curl --location 'http://localhost:8080/user/role' \ --header 'authorization: Bearer JWT' \ --header 'cookie: login_token=JWT' \ --data '{ "role_scope": "profile", "entity_type": "merchant", "groups": [ "operations_view", "operations_manage" ], "role_name": "merchant-role-at-profile-scope" }' ``` Response ``` { "error": { "type": "invalid_request", "message": "User Role Operation Not Supported", "code": "UR_23" } } ``` ## 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.113.0
bca8979a0cd25472b2f9b5e9d9daf7509a7b3cbb
bca8979a0cd25472b2f9b5e9d9daf7509a7b3cbb
juspay/hyperswitch
juspay__hyperswitch-7852
Bug: [CHORE] remove billing details are required fields from Worldpay Worldpay does not mandate sending billing address during payment create request. These fields are needed to be removed as required fields which are configured as a part of dynamic required fields for payment widget.
diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 175b82192b4..2f4fb7a8013 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -1450,23 +1450,6 @@ fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { RequiredField::CardNumber, RequiredField::CardExpMonth, RequiredField::CardExpYear, - RequiredField::BillingAddressLine1, - RequiredField::BillingAddressCountries(vec![ - "AF", "AU", "AW", "AZ", "BS", "BH", "BD", "BB", "BZ", "BM", "BT", "BO", - "BA", "BW", "BR", "BN", "BG", "BI", "KH", "CA", "CV", "KY", "CL", "CO", - "KM", "CD", "CR", "CZ", "DZ", "DK", "DJ", "ST", "DO", "EC", "EG", "SV", - "ER", "ET", "FK", "FJ", "GM", "GE", "GH", "GI", "GT", "GN", "GY", "HT", - "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IL", "IT", "JM", - "JP", "JO", "KZ", "KE", "KW", "LA", "LB", "LS", "LR", "LY", "LT", "MO", - "MK", "MG", "MW", "MY", "MV", "MR", "MU", "MX", "MD", "MN", "MA", "MZ", - "MM", "NA", "NZ", "NI", "NG", "KP", "NO", "AR", "PK", "PG", "PY", "PE", - "UY", "PH", "PL", "GB", "QA", "OM", "RO", "RU", "RW", "WS", "SG", "ST", - "ZA", "KR", "LK", "SH", "SD", "SR", "SZ", "SE", "CH", "SY", "TW", "TJ", - "TZ", "TH", "TT", "TN", "TR", "UG", "UA", "US", "UZ", "VU", "VE", "VN", - "ZM", "ZW", - ]), - RequiredField::BillingAddressCity, - RequiredField::BillingAddressZip, ], ), ),
2025-04-18T11:38:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR removes billing details as required fields for Worldpay 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 This change helps in not showing the billing details as required fields on the payment widget. ## How did you test it? Locally, by rendering payment links. <details> <summary>Fetch account payment method list</summary> cURL curl 'http://localhost:8080/account/payment_methods?client_secret=pay_62mvQc0WyVZ5pe8QxqhR_secret_K6C6bulFCe6jdm6GogvF' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:137.0) Gecko/20100101 Firefox/137.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' -H 'Accept-Encoding: gzip, deflate, br, zstd' -H 'Referer: http://localhost:9050/' -H 'api-key: pk_dev_36edab4ded2a4a8abdbcffaa254eb7e4' -H 'content-type: application/json' -H 'x-browser-name: Firefox' -H 'x-browser-version: 137.0' -H 'x-client-platform: web' -H 'x-client-version: 0.122.6' -H 'x-payment-confirm-source: sdk' -H 'Origin: http://localhost:9050' -H 'Connection: keep-alive' -H 'Sec-Fetch-Dest: empty' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Site: same-site' -H 'Priority: u=4' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' Response { "redirect_url": "https://google.com/success", "currency": "EUR", "payment_methods": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "worldpay" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "worldpay" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "is_tax_calculation_enabled": false } </details> ## 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.113.0
eabef328c665cfbaf953a5eb15bd15484c62dcf7
eabef328c665cfbaf953a5eb15bd15484c62dcf7
juspay/hyperswitch
juspay__hyperswitch-7880
Bug: [Refactor] Remove merchant reference id from customers v2 update api Remove `merchant_reference_id` field from customer update request struct so that it cannot be updated.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 10682866ab7..f7f62fe5ee8 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -9362,14 +9362,6 @@ "email" ], "properties": { - "merchant_reference_id": { - "type": "string", - "description": "The merchant identifier for the customer object.", - "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44", - "nullable": true, - "maxLength": 64, - "minLength": 1 - }, "name": { "type": "string", "description": "The customer's name", diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs index eb61cae6e47..90f849971b2 100644 --- a/crates/api_models/src/customers.rs +++ b/crates/api_models/src/customers.rs @@ -313,9 +313,6 @@ impl CustomerUpdateRequest { #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerUpdateRequest { - /// The merchant identifier for the customer object. - #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] - pub merchant_reference_id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = String, example = "Jon Test")] pub name: Option<Secret<String>>, @@ -349,10 +346,6 @@ pub struct CustomerUpdateRequest { #[cfg(all(feature = "v2", feature = "customer_v2"))] impl CustomerUpdateRequest { - pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { - self.merchant_reference_id.clone() - } - pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> { self.default_billing_address.clone() }
2025-04-23T09:07:12Z
## 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 --> We are removing `merchant_reference_id` from all API updates, due to possible bugs on merchant side db and HS db as there might be mismatch in their's and our's db records. This exists only in customers and refunds v2 apis, a separate PR has been implemented for refunds update, and this PR is for customers v2 update api. It was noticed that in the current implementation of customers v2 update flow, the `merchant_reference_id` field is being accepted by the API but it was never updated in the db. In this PR we are removing `merchant_reference_id` from being accepted in the customers v2 update request. ### 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). --> Upon merging this PR, we will be removing `merchant_reference_id` from being updated in customer v2 update api. ## 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 Customer API Call ``` curl --location 'http://localhost:8080/v2/customers' \ --header 'x-profile-id: pro_saOFnM13wT1ngOuItKJl' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_VAtwaBd0cVItaaxIS8bUTFuPcxa9DkqlmBPvH5fq6IASKSlBxc9cBUygLoCaebFj' \ --data-raw '{ "merchant_reference_id": "customer_1748929359", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "default_billing_address": null, "default_shipping_address": null, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Response from above call ``` { "id": "12345_cus_0197344f74677930a77bfc4c926c3b3e", "merchant_reference_id": "customer_1748929312", "connector_customer_ids": null, "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "default_billing_address": null, "default_shipping_address": null, "created_at": "2025-06-03T05:41:51.849Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null } ``` - Customer Update API call ``` curl --location --request PUT 'http://localhost:8080/v2/customers/12345_cus_0197344f74677930a77bfc4c926c3b3e' \ --header 'x-profile-id: pro_saOFnM13wT1ngOuItKJl' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_VAtwaBd0cVItaaxIS8bUTFuPcxa9DkqlmBPvH5fq6IASKSlBxc9cBUygLoCaebFj' \ --data-raw '{ "name": "Jane Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "Second customer", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Response from the above call ``` { "id": "12345_cus_0197344f74677930a77bfc4c926c3b3e", "merchant_reference_id": "customer_1748929312", "connector_customer_ids": null, "name": "Jane Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "Second customer", "default_billing_address": null, "default_shipping_address": null, "created_at": "2025-06-03T05:41:51.849Z", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "default_payment_method_id": null } ``` - Trying to update `merchant_reference_id` API call ``` curl --location --request PUT 'http://localhost:8080/v2/customers/12345_cus_0197344f74677930a77bfc4c926c3b3e' \ --header 'x-profile-id: pro_saOFnM13wT1ngOuItKJl' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_VAtwaBd0cVItaaxIS8bUTFuPcxa9DkqlmBPvH5fq6IASKSlBxc9cBUygLoCaebFj' \ --data-raw '{ "merchant_reference_id": "customer_1748929499", "name": "Jane Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65", "description": "Second customer", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Response from the above call ``` { "error": { "error_type": "invalid_request", "message": "Json deserialize error: unknown field `merchant_reference_id`, expected one of `name`, `email`, `phone`, `description`, `phone_country_code`, `default_billing_address`, `default_shipping_address`, `metadata`, `default_payment_method_id` at line 2 column 27", "code": "IR_06" } } ``` ## 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.114.0
639b8cba5fff2aeb85787309983e412b4a21b238
639b8cba5fff2aeb85787309983e412b4a21b238
juspay/hyperswitch
juspay__hyperswitch-7875
Bug: feat(merchant_context): add struct `merchant_context` and replace all instances of `merchant_account` and `key_store` in core # Introduction of MerchantContext: Unified Merchant Operation Context ## Challenge Currently, merchant account and key store information are passed separately throughout the codebase, leading to scattered merchant context handling and reduced maintainability. Functions individually manage these components, making it difficult to implement platform-wide features or connected account capabilities. ## Proposed Changes Introducing `MerchantContext`, a new type that encapsulates both merchant account and key store information: ```rust pub enum MerchantContext { NormalMerchant(Box<Context>), } pub struct Context(pub MerchantAccount, pub MerchantKeyStore); ``` The type provides controlled access through methods: - `get_merchant_account()`: Access merchant account details - `get_merchant_key_store()`: Access cryptographic key store ## Why 1. **Unified Context**: Encapsulates merchant authentication and operational context in one place 2. **Cleaner Architecture**: Replaces scattered merchant account and key store parameters with a single context object 3. **Enhanced Control**: Method-based access enables validation, transformation, and future enhancements 4. **Maintainability**: Centralized merchant context management reduces code duplication and improves traceability ## How The implementation follows a tree-like flow where the `MerchantContext` is: 1. Declared at the route handler level (root) 2. Passed down through core operation handlers (branches) 3. Finally consumed in database operations or other terminal functions (leaves) This creates a clear, traceable flow of merchant context through the entire operation chain, making it easier to understand and maintain merchant-related operations. ## Future Objectives 1. **Operational Context extension**: The enum structure allows adding new variants for different operations, enabling: - Platform-level context inheritance - Connected account operations - cherry picking context for individual fragment of flows 2. **Granular Context Control**: - Move context declaration to auth layer - Enable advanced platform features by implementing context creation logic for platform operations This architectural change sets the foundation for future platform features while maintaining current functionality and improving code organization.
2025-04-23T09:26:46Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD This PR introduces a new `MerchantContext` type that unifies merchant account and key store information into a single, controlled-access context object. The implementation includes: 1. New `MerchantContext` enum and `Context` struct definitions 2. Method-based access control for merchant account and key store information 3. Tree-like flow implementation for context propagation through the application 4. Foundation for future platform-level features and connected account operations ```rust pub enum MerchantContext { NormalMerchant(Box<Context>), } pub struct Context(pub MerchantAccount, pub MerchantKeyStore); ``` The type provides controlled access through methods: - `get_merchant_account()`: Access merchant account details - `get_merchant_key_store()`: Access cryptographic key store The changes primarily affect the merchant context handling throughout the codebase, replacing scattered parameter passing with a unified context object. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context ### Fixes [#7875](https://github.com/juspay/hyperswitch/issues/7875) The current implementation has several limitations: 1. Merchant account and key store information are passed separately throughout the codebase 2. Scattered merchant context handling reduces maintainability 3. Individual functions managing these components make it difficult to implement vsaas related (platform) features 4. Lack of centralized control for merchant context operations This refactoring addresses these issues by: 1. Encapsulating merchant authentication and operational context in one place 2. Providing a cleaner architecture with a single context object 3. Enabling method-based access for validation and transformation n The changes set the foundation for future enhancements including: - Platform-level context inheritance - Connected account operations - Granular context control at the auth layer (being added). - Advanced platform features through context creation logic (to be added). ## How did you test it? #### **Important** The changes included in this PR don't affect any flows or behaviour, it is merely a refactor of the whole core module. Test method: Ran ```cargo hack ``` locally and ran all sanity checks. #### Some core operations cURLs ##### Merchant account creation ```bash curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: REDACTED' \ --data-raw '{ "merchant_id": "merchant_1745407533", "locker_id": "m0010", "merchant_name": "NewAge Retailer", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "[email protected]", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "[email protected]", "secondary_phone": "cillum do dolor id", "website": "https://www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name":"john", "last_name":"Doe" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url":"https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "parent_merchant_id":"merchant_123", "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` Res: ```json { "merchant_id": "merchant_1745407536", "merchant_name": "NewAge Retailer", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "h63lzU5pCbN8pzP9gOiWZLu8deQRy5fNMtCGa8vDoMBMqZVOyd4mL22dcSPrYLkB", "redirect_to_merchant_with_http_post": false, "merchant_details": { "primary_contact_person": "John Test", "primary_phone": "sunt laborum", "primary_email": "[email protected]", "secondary_contact_person": "John Test2", "secondary_phone": "cillum do dolor id", "secondary_email": "[email protected]", "website": "https://www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" } }, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": "https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "payout_routing_algorithm": null, "sub_merchants_enabled": false, "parent_merchant_id": null, "publishable_key": "pk_dev_170e697c79ae4f128825aec6246761cd", "metadata": { "city": "NY", "unit": "245", "compatible_connector": null }, "locker_id": "m0010", "primary_business_details": [ { "country": "US", "business": "default" } ], "frm_routing_algorithm": null, "organization_id": "org_KQ4zLFbq0TKr7pvG59Va", "is_recon_enabled": false, "default_profile": "pro_9P0eWVliPBMEzYLqeejN", "recon_status": "not_requested", "pm_collect_link_config": null, "product_type": "orchestration" } ``` ##### Payment ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: REDACTED' \ --data-raw '{ "amount": 104000, "currency": "GBP", "amount_to_capture": 104000, "confirm": true, "profile_id": "pro_A5v5oJ8JhYmVDdJPiOGe", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "routing": { "type": "single", "data": "stripe" }, "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4532432452900131", "card_exp_month": "01", "card_exp_year": "99", "card_holder_name": "John Smith", "card_cvc": "257" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 104000, "account_name": "transaction_processing" } ], "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal", "request_incremental_authorization": false, "merchant_order_reference_id": "test_ord", "session_expiry": 900 }' ``` Res: ```json { "payment_id": "pay_DcEBzqxP2qQ5mCDygEIu", "merchant_id": "merchant_1745478997", "status": "failed", "amount": 104000, "net_amount": 104000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "pay_DcEBzqxP2qQ5mCDygEIu_secret_YfbAUlzs6BFc3UFkandB", "created": "2025-04-24T07:21:25.127Z", "currency": "GBP", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0131", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453243", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "99", "card_holder_name": "John Smith", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 104000, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": "John Doe", "phone": "9999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": "DC_04", "error_message": "Card not supported. Please use test cards", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1745479285, "expires": 1745482885, "secret": "epk_64adcfbf68f24d77be6ee26af56e90c6" }, "manual_retry_allowed": true, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" }, "braintree": null }, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_A5v5oJ8JhYmVDdJPiOGe", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_MUYcgcVSOudbAphvZGRR", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-24T07:36:25.127Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-24T07:21:26.203Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "test_ord", "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` ## Checklist - [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.113.0
3d0dd5bd1a8d764757fce4a37c668c0ff548d59c
3d0dd5bd1a8d764757fce4a37c668c0ff548d59c
juspay/hyperswitch
juspay__hyperswitch-7870
Bug: Add support for caching and resolving last used lineage context Currently, after a user logs in and switches between merchants or profiles, their context is **not remembered** across sessions. Each new login resolves the default role from the DB and starts with a clean slate. This leads to: - Poor user experience for users with multiple roles - Repetitive DB queries for every login - No continuity across logins for previously active merchant/profile context ### Objective Introduce a mechanism to **cache the last used lineage context** (`org_id`, `merchant_id`, `profile_id`, `role_id`, `tenant_id`) in Redis and use it for JWT generation on subsequent logins. ### Expected Behavior - During login: - If lineage context exists in Redis → use it to validate and generate the JWT. - If not found or invalid → fallback to default DB-based user role resolution. - During merchant/profile switch: - Store the latest lineage context in Redis for future use. - Redis entries should have a **TTL of 7 days** to auto-expire for inactive users.
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 4f681cda25b..649b8820859 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -41,3 +41,6 @@ pub const REDIS_SSO_TTL: i64 = 5 * 60; // 5 minutes pub const DEFAULT_PROFILE_NAME: &str = "default"; pub const DEFAULT_PRODUCT_TYPE: common_enums::MerchantProductType = common_enums::MerchantProductType::Orchestration; + +pub const LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS: i64 = 60 * 60 * 24 * 7; // 7 days +pub const LINEAGE_CONTEXT_PREFIX: &str = "LINEAGE_CONTEXT_"; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 91b20621da8..6e5360d8848 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -3169,6 +3169,23 @@ pub async fn switch_org_for_user( } }; + let lineage_context = domain::LineageContext { + user_id: user_from_token.user_id.clone(), + merchant_id: merchant_id.clone(), + role_id: role_id.clone(), + org_id: request.org_id.clone(), + profile_id: profile_id.clone(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id) + .clone(), + }; + + lineage_context + .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) + .await; + let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, @@ -3364,6 +3381,23 @@ pub async fn switch_merchant_for_user_in_org( } }; + let lineage_context = domain::LineageContext { + user_id: user_from_token.user_id.clone(), + merchant_id: merchant_id.clone(), + role_id: role_id.clone(), + org_id: org_id.clone(), + profile_id: profile_id.clone(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id) + .clone(), + }; + + lineage_context + .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) + .await; + let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, @@ -3480,6 +3514,23 @@ pub async fn switch_profile_for_user_in_org_and_merchant( } }; + let lineage_context = domain::LineageContext { + user_id: user_from_token.user_id.clone(), + merchant_id: user_from_token.merchant_id.clone(), + role_id: role_id.clone(), + org_id: user_from_token.org_id.clone(), + profile_id: profile_id.clone(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id) + .clone(), + }; + + lineage_context + .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) + .await; + let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 8bf177035ef..016995cb550 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -23,7 +23,7 @@ use hyperswitch_domain_models::api::ApplicationResponse; use masking::{ExposeInterface, PeekInterface, Secret}; use once_cell::sync::Lazy; use rand::distributions::{Alphanumeric, DistString}; -use router_env::env; +use router_env::{env, logger}; use time::PrimitiveDateTime; use unicode_segmentation::UnicodeSegmentation; #[cfg(feature = "keymanager_create")] @@ -39,7 +39,7 @@ use crate::{ routes::SessionState, services::{self, authentication::UserFromToken}, types::{domain, transformers::ForeignFrom}, - utils::user::password, + utils::{self, user::password}, }; pub mod dashboard_metadata; @@ -1458,3 +1458,54 @@ where .change_context(UserErrors::InternalServerError) } } + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct LineageContext { + pub user_id: String, + pub merchant_id: id_type::MerchantId, + pub role_id: String, + pub org_id: id_type::OrganizationId, + pub profile_id: id_type::ProfileId, + pub tenant_id: id_type::TenantId, +} + +impl LineageContext { + pub async fn try_get_lineage_context_from_cache( + state: &SessionState, + user_id: &str, + ) -> Option<Self> { + // The errors are not handled here because we don't want to fail the request if the cache operation fails. + // The errors are logged for debugging purposes. + match utils::user::get_lineage_context_from_cache(state, user_id).await { + Ok(Some(ctx)) => Some(ctx), + Ok(None) => { + logger::debug!("Lineage context not found in Redis for user {}", user_id); + None + } + Err(e) => { + logger::error!( + "Failed to retrieve lineage context from Redis for user {}: {:?}", + user_id, + e + ); + None + } + } + } + + pub async fn try_set_lineage_context_in_cache(&self, state: &SessionState, user_id: &str) { + // The errors are not handled here because we don't want to fail the request if the cache operation fails. + // The errors are logged for debugging purposes. + if let Err(e) = + utils::user::set_lineage_context_in_cache(state, user_id, self.clone()).await + { + logger::error!( + "Failed to set lineage context in Redis for user {}: {:?}", + user_id, + e + ); + } else { + logger::debug!("Lineage context cached for user {}", user_id); + } + } +} diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index bf5556dd9a7..0214d3cdd15 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -1,6 +1,9 @@ use common_enums::TokenPurpose; use common_utils::id_type; -use diesel_models::{enums::UserStatus, user_role::UserRole}; +use diesel_models::{ + enums::{UserRoleVersion, UserStatus}, + user_role::UserRole, +}; use error_stack::ResultExt; use masking::Secret; @@ -10,6 +13,7 @@ use crate::{ db::user_role::ListUserRolesByUserIdPayload, routes::SessionState, services::authentication as auth, + types::domain::LineageContext, utils, }; @@ -124,23 +128,93 @@ impl JWTFlow { next_flow: &NextFlow, user_role: &UserRole, ) -> UserResult<Secret<String>> { + let user_id = next_flow.user.get_user_id(); + let cached_lineage_context = + LineageContext::try_get_lineage_context_from_cache(state, user_id).await; + + let new_lineage_context = match cached_lineage_context { + Some(ctx) => { + let tenant_id = ctx.tenant_id.clone(); + let user_role_match_v1 = state + .global_store + .find_user_role_by_user_id_and_lineage( + &ctx.user_id, + &tenant_id, + &ctx.org_id, + &ctx.merchant_id, + &ctx.profile_id, + UserRoleVersion::V1, + ) + .await + .is_ok(); + + if user_role_match_v1 { + ctx + } else { + let user_role_match_v2 = state + .global_store + .find_user_role_by_user_id_and_lineage( + &ctx.user_id, + &tenant_id, + &ctx.org_id, + &ctx.merchant_id, + &ctx.profile_id, + UserRoleVersion::V2, + ) + .await + .is_ok(); + + if user_role_match_v2 { + ctx + } else { + // fallback to default lineage if cached context is invalid + Self::resolve_lineage_from_user_role(state, user_role, user_id).await? + } + } + } + None => + // no cached context found + { + Self::resolve_lineage_from_user_role(state, user_role, user_id).await? + } + }; + + new_lineage_context + .try_set_lineage_context_in_cache(state, user_id) + .await; + + auth::AuthToken::new_token( + new_lineage_context.user_id, + new_lineage_context.merchant_id, + new_lineage_context.role_id, + &state.conf, + new_lineage_context.org_id, + new_lineage_context.profile_id, + Some(new_lineage_context.tenant_id), + ) + .await + .map(|token| token.into()) + } + + pub async fn resolve_lineage_from_user_role( + state: &SessionState, + user_role: &UserRole, + user_id: &str, + ) -> UserResult<LineageContext> { let org_id = utils::user_role::get_single_org_id(state, user_role).await?; let merchant_id = utils::user_role::get_single_merchant_id(state, user_role, &org_id).await?; let profile_id = utils::user_role::get_single_profile_id(state, user_role, &merchant_id).await?; - auth::AuthToken::new_token( - next_flow.user.get_user_id().to_string(), - merchant_id, - user_role.role_id.clone(), - &state.conf, + Ok(LineageContext { + user_id: user_id.to_string(), org_id, + merchant_id, profile_id, - Some(user_role.tenant_id.clone()), - ) - .await - .map(|token| token.into()) + role_id: user_role.role_id.clone(), + tenant_id: user_role.tenant_id.clone(), + }) } } diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 89612fc1892..3e339a2a570 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -12,7 +12,10 @@ use redis_interface::RedisConnectionPool; use router_env::env; use crate::{ - consts::user::{REDIS_SSO_PREFIX, REDIS_SSO_TTL}, + consts::user::{ + LINEAGE_CONTEXT_PREFIX, LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS, REDIS_SSO_PREFIX, + REDIS_SSO_TTL, + }, core::errors::{StorageError, UserErrors, UserResult}, routes::SessionState, services::{ @@ -20,7 +23,7 @@ use crate::{ authorization::roles::RoleInfo, }, types::{ - domain::{self, MerchantAccount, UserFromStorage}, + domain::{self, LineageContext, MerchantAccount, UserFromStorage}, transformers::ForeignFrom, }, }; @@ -339,3 +342,49 @@ pub async fn validate_email_domain_auth_type_using_db( .then_some(()) .ok_or(UserErrors::InvalidUserAuthMethodOperation.into()) } + +pub async fn get_lineage_context_from_cache( + state: &SessionState, + user_id: &str, +) -> UserResult<Option<LineageContext>> { + let connection = get_redis_connection(state)?; + let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); + let lineage_context = connection + .get_key::<Option<String>>(&key.into()) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get lineage context from redis")?; + + match lineage_context { + Some(json_str) => { + let ctx = serde_json::from_str::<LineageContext>(&json_str) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to deserialize LineageContext from JSON")?; + Ok(Some(ctx)) + } + None => Ok(None), + } +} + +pub async fn set_lineage_context_in_cache( + state: &SessionState, + user_id: &str, + lineage_context: LineageContext, +) -> UserResult<()> { + let connection = get_redis_connection(state)?; + let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); + let serialized_lineage_context: String = serde_json::to_string(&lineage_context) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to serialize LineageContext")?; + connection + .set_key_with_expiry( + &key.into(), + serialized_lineage_context, + LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to set lineage context in redis")?; + + Ok(()) +}
2025-04-22T14:54:00Z
## 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 lineage context caching to enhance login and account-switch flows with better continuity and reduced DB load. ### Key Changes - **During Login:** - Attempt to fetch the last used `LineageContext` from Redis (`LINEAGE_CONTEXT_<user_id>`). - If context is found: - Validate whether a matching user role exists (using both `V1` and `V2` role versions). - If a valid user_role is found → use this lineage context to issue the JWT token. - If not → fallback to the default user_role-based resolution logic. - If context is **not found in cache**, fallback to the existing login flow entirely. - **During Account Switch:** - After switching org/merchant/profile context and issuing the new JWT token, the new `LineageContext` is saved to Redis (`LINEAGE_CONTEXT_<user_id>`). - This allows restoring the last used org/merchant/profile on future logins. - **Redis Cache Expiry:** - Cached lineage context entries are stored with a TTL of **7 days**. - If the user is inactive beyond this duration, the system reverts to default logic. ### 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). --> - Improves user experience by remembering their last used account context across sessions. - Reduces unnecessary DB lookups during login for returning users. - Ensures fallback safety in case of invalid or expired lineage context. ## 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 locally with TTL as 1 minute, keys are getting stored in redis <img width="1065" alt="Screenshot 2025-04-22 at 7 40 32 PM" src="https://github.com/user-attachments/assets/1201a92b-7957-4075-8ec6-9a75376c842a" /> <img width="1369" alt="image" src="https://github.com/user-attachments/assets/2e8fbec0-a1e1-4ef9-b280-67ccbea7b1d1" /> ![Screenshot 2025-04-22 at 7 41 43 PM](https://github.com/user-attachments/assets/b0cdf010-0828-4982-98a4-91625d707c84) ### Test 1: - Log in to the merchant account. - Check redis using the key: ```GET LINEAGE_CONTEXT_<user_id>``` The value should contain the last used lineage context for the user. - Switch to another org/merchant/profile. - Recheck redis with the same key: ```GET LINEAGE_CONTEXT_<user_id>```. The lineage should now be changed. ### Test 2: - After the above test, log out and log in back, within the TTL for the lineage_context, which is 7 days. - You should be logged in to exactly the same lineage which you last used. ### Test 3 (optional): - Have a note of the lineage. - Do not use this account for 7 days. - Try logging in now. - You should be logged in to a random account (possibly the lineage which you have not used last) - This proves, that the key has expired and the default fallback login is now used. ## 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.113.0
776bde00efce8be35e0c63c1bdc6215921babddf
776bde00efce8be35e0c63c1bdc6215921babddf
juspay/hyperswitch
juspay__hyperswitch-7872
Bug: [FEATURE] (connector): [GETNET,HIPAY,KLARNA,MONERIS,OPENNODE] add in feature matrix api ### Feature Description [GETNET,HIPAY,KLARNA,MONERIS,OPENNODE] add in feature matrix api ### Possible Implementation [GETNET,HIPAY,KLARNA,MONERIS,OPENNODE] add in feature matrix api ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index 5f13eb1388d..96c435f369f 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -471,8 +471,8 @@ slack_invite_url = "https://www.example.com/" # Slack invite url for hyperswit discord_invite_url = "https://www.example.com/" # Discord invite url for hyperswitch [mandates.supported_payment_methods] -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" wallet.paypal = { connector_list = "adyen,novalnet" } # Mandate supported payment method type and connector for wallets pay_later.klarna = { connector_list = "adyen" } # Mandate supported payment method type and connector for pay_later bank_debit.ach = { connector_list = "gocardless,adyen" } # Mandate supported payment method type and connector for bank_debit diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index d7eb52a81e3..4b057cee228 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -177,8 +177,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" @@ -313,6 +313,20 @@ debit = { country = "DE, DK, FR, SE", currency = "DKK, NOK" } credit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } +[pm_filters.getnet] +credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" } + +[pm_filters.hipay] +credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } +debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } + +[pm_filters.moneris] +credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } +debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } + +[pm_filters.opennode] +crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } + [pm_filters.authorizedotnet] google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" paypal.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 1cde8c3079a..1f96521d3d1 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -177,8 +177,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" @@ -327,6 +327,20 @@ debit = { country = "DE, DK, FR, SE", currency = "DKK, NOK" } credit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } +[pm_filters.getnet] +credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" } + +[pm_filters.hipay] +credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } +debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } + +[pm_filters.moneris] +credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } +debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } + +[pm_filters.opennode] +crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } + [pm_filters.authorizedotnet] google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" paypal.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 4059ba2ccb2..d120205d03f 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -177,8 +177,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" @@ -329,6 +329,20 @@ debit = { country = "DE, DK, FR, SE", currency = "DKK, NOK" } credit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } +[pm_filters.getnet] +credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" } + +[pm_filters.hipay] +credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } +debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } + +[pm_filters.moneris] +credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } +debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } + +[pm_filters.opennode] +crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } + [pm_filters.authorizedotnet] google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" paypal.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" diff --git a/config/development.toml b/config/development.toml index 89e35448af2..1741202d780 100644 --- a/config/development.toml +++ b/config/development.toml @@ -555,6 +555,20 @@ debit = { country = "DE, DK, FR, SE", currency = "DKK, NOK" } credit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } +[pm_filters.getnet] +credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" } + +[pm_filters.hipay] +credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } +debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } + +[pm_filters.moneris] +credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } +debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } + +[pm_filters.opennode] +crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } + [pm_filters.bambora] credit = { country = "US,CA", currency = "USD" } debit = { country = "US,CA", currency = "USD" } @@ -819,8 +833,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index cdf82f60936..63d6f96ff66 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -479,6 +479,20 @@ debit = { country = "DE, DK, FR, SE", currency = "DKK, NOK" } credit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "DE, FR, IT, NL, PL, ES, ZA, GB, AE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } +[pm_filters.getnet] +credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" } + +[pm_filters.hipay] +credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } +debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } + +[pm_filters.moneris] +credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } +debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } + +[pm_filters.opennode] +crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } + [pm_filters.bambora] credit = { country = "US,CA", currency = "USD" } debit = { country = "US,CA", currency = "USD" } diff --git a/crates/hyperswitch_connectors/src/connectors/getnet.rs b/crates/hyperswitch_connectors/src/connectors/getnet.rs index 06bd210431a..1aa41c801ee 100644 --- a/crates/hyperswitch_connectors/src/connectors/getnet.rs +++ b/crates/hyperswitch_connectors/src/connectors/getnet.rs @@ -1,4 +1,6 @@ pub mod transformers; +use std::sync::LazyLock; + use api_models::webhooks::IncomingWebhookEvent; use base64::{self, Engine}; use common_enums::enums; @@ -23,7 +25,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -163,23 +168,6 @@ impl ConnectorCommon for Getnet { } impl ConnectorValidation for Getnet { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual - | enums::CaptureMethod::SequentialAutomatic => Ok(()), - enums::CaptureMethod::Scheduled | enums::CaptureMethod::ManualMultiple => Err( - utils::construct_not_implemented_error_report(capture_method, self.id()), - ), - } - } - fn validate_psync_reference_id( &self, data: &PaymentsSyncData, @@ -829,4 +817,70 @@ impl webhooks::IncomingWebhook for Getnet { } } -impl ConnectorSpecifications for Getnet {} +static GETNET_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + common_enums::CardNetwork::RuPay, + common_enums::CardNetwork::Maestro, + ]; + + let mut getnet_supported_payment_methods = SupportedPaymentMethods::new(); + + getnet_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network, + } + }), + ), + }, + ); + + getnet_supported_payment_methods +}); + +static GETNET_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Getnet", + description: "Getnet is a high-tech global payment platform that helps businesses accept payments securely while providing the best frictionless experience for customers everywhere.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static GETNET_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] = + [enums::EventClass::Payments, enums::EventClass::Refunds]; + +impl ConnectorSpecifications for Getnet { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&GETNET_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*GETNET_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&GETNET_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/hipay.rs b/crates/hyperswitch_connectors/src/connectors/hipay.rs index d58c81c737d..c0d02156ebc 100644 --- a/crates/hyperswitch_connectors/src/connectors/hipay.rs +++ b/crates/hyperswitch_connectors/src/connectors/hipay.rs @@ -1,6 +1,8 @@ pub mod transformers; +use std::sync::LazyLock; + use base64::Engine; -use common_enums::{CaptureMethod, PaymentMethod, PaymentMethodType}; +use common_enums::{enums, CaptureMethod, PaymentMethod, PaymentMethodType}; use common_utils::{ consts::BASE64_ENGINE, errors::{self as common_errors, CustomResult}, @@ -21,7 +23,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData, @@ -251,28 +256,7 @@ impl ConnectorCommon for Hipay { } } -impl ConnectorValidation for Hipay { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<CaptureMethod>, - _payment_method: PaymentMethod, - _pmt: Option<PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - CaptureMethod::Automatic - | CaptureMethod::Manual - | CaptureMethod::SequentialAutomatic => Ok(()), - CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => { - Err(errors::ConnectorError::NotSupported { - message: capture_method.to_string(), - connector: self.id(), - } - .into()) - } - } - } -} +impl ConnectorValidation for Hipay {} impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Hipay {} @@ -768,4 +752,86 @@ impl webhooks::IncomingWebhook for Hipay { } } -impl ConnectorSpecifications for Hipay {} +static HIPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + CaptureMethod::Automatic, + CaptureMethod::Manual, + CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + ]; + + let mut hipay_supported_payment_methods = SupportedPaymentMethods::new(); + + hipay_supported_payment_methods.add( + PaymentMethod::Card, + PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + hipay_supported_payment_methods.add( + PaymentMethod::Card, + PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + hipay_supported_payment_methods +}); + +static HIPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Hipay", + description: "HiPay is an independent global payment service provider that is based in France.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static HIPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Hipay { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&HIPAY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*HIPAY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&HIPAY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/klarna.rs b/crates/hyperswitch_connectors/src/connectors/klarna.rs index d2be42a1828..03ef376fbbe 100644 --- a/crates/hyperswitch_connectors/src/connectors/klarna.rs +++ b/crates/hyperswitch_connectors/src/connectors/klarna.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use api_models::webhooks::IncomingWebhookEvent; use base64::Engine; use common_enums::enums; @@ -24,7 +26,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSessionRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -50,8 +55,8 @@ use crate::{ constants::headers, types::ResponseRouterData, utils::{ - construct_not_supported_error_report, convert_amount, get_http_header, - get_unimplemented_payment_method_error_message, missing_field_err, RefundsRequestData, + convert_amount, get_http_header, get_unimplemented_payment_method_error_message, + missing_field_err, RefundsRequestData, }, }; @@ -133,24 +138,7 @@ impl ConnectorCommon for Klarna { } } -impl ConnectorValidation for Klarna { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual - | enums::CaptureMethod::SequentialAutomatic => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - construct_not_supported_error_report(capture_method, self.id()), - ), - } - } -} +impl ConnectorValidation for Klarna {} impl api::Payment for Klarna {} @@ -1369,4 +1357,47 @@ impl IncomingWebhook for Klarna { } } -impl ConnectorSpecifications for Klarna {} +static KLARNA_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut klarna_supported_payment_methods = SupportedPaymentMethods::new(); + + klarna_supported_payment_methods.add( + enums::PaymentMethod::PayLater, + enums::PaymentMethodType::Klarna, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: None, + }, + ); + + klarna_supported_payment_methods +}); + +static KLARNA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Klarna", + description: "Klarna provides payment processing services for the e-commerce industry, managing store claims and customer payments.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static KLARNA_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Klarna { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&KLARNA_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*KLARNA_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&KLARNA_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/moneris.rs b/crates/hyperswitch_connectors/src/connectors/moneris.rs index ae4832b5597..fffd71a4e0b 100644 --- a/crates/hyperswitch_connectors/src/connectors/moneris.rs +++ b/crates/hyperswitch_connectors/src/connectors/moneris.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; + use common_enums::enums; use common_utils::{ errors::CustomResult, @@ -20,7 +22,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData, @@ -182,23 +187,6 @@ impl ConnectorCommon for Moneris { } impl ConnectorValidation for Moneris { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), - enums::CaptureMethod::ManualMultiple - | enums::CaptureMethod::Scheduled - | enums::CaptureMethod::SequentialAutomatic => Err( - utils::construct_not_implemented_error_report(capture_method, self.id()), - ), - } - } - fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, @@ -819,4 +807,85 @@ impl webhooks::IncomingWebhook for Moneris { } } -impl ConnectorSpecifications for Moneris {} +static MONERIS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + ]; + + let mut moneris_supported_payment_methods = SupportedPaymentMethods::new(); + + moneris_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + moneris_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + moneris_supported_payment_methods +}); + +static MONERIS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Moneris", + description: "Moneris is Canada's top payment solutions provider, empowering businesses with innovative mobile, online & in-store solutions.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static MONERIS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Moneris { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&MONERIS_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*MONERIS_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&MONERIS_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/opennode.rs b/crates/hyperswitch_connectors/src/connectors/opennode.rs index dde5b9adfcd..5ce75b4332d 100644 --- a/crates/hyperswitch_connectors/src/connectors/opennode.rs +++ b/crates/hyperswitch_connectors/src/connectors/opennode.rs @@ -1,7 +1,8 @@ pub mod transformers; -use std::fmt::Debug; +use std::{fmt::Debug, sync::LazyLock}; +use common_enums::enums; use common_utils::{ crypto, errors::CustomResult, @@ -21,7 +22,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundsRouterData, @@ -439,4 +443,45 @@ impl IncomingWebhook for Opennode { } } -impl ConnectorSpecifications for Opennode {} +static OPENNODE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = vec![enums::CaptureMethod::Automatic]; + + let mut opennode_supported_payment_methods = SupportedPaymentMethods::new(); + + opennode_supported_payment_methods.add( + enums::PaymentMethod::Crypto, + enums::PaymentMethodType::CryptoCurrency, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::NotSupported, + supported_capture_methods, + specific_features: None, + }, + ); + + opennode_supported_payment_methods + }); + +static OPENNODE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Opennode", + description: + "OpenNode offers accessible way for e-commerce businesses to process bitcoin payments.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static OPENNODE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; + +impl ConnectorSpecifications for Opennode { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&OPENNODE_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*OPENNODE_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&OPENNODE_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index b0c4d7f3a38..f32f5a34e33 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -397,6 +397,23 @@ sofort = { country = "AT,BE,CH,DE,ES,FI,FR,GB,IT,NL,PL,SE", currency = "CHF,EUR" credit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } +[pm_filters.getnet] +credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" } + +[pm_filters.hipay] +credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } +debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" } + +[pm_filters.moneris] +credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } +debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" } + +[pm_filters.opennode] +crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } + +[pm_filters.klarna] +klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } + #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } @@ -438,8 +455,8 @@ bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris" pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource"
2025-04-22T18:29:30Z
## 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/7872) ## Description <!-- Describe your changes in detail --> Added Getnet, Hipay, Klarna, Moneris, Opennode in feature matrix API ### 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 Tests Request: ``` curl --location 'http://localhost:8080/feature_matrix' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header '[api-key]' ``` Response: ``` { "connector_count": 5, "connectors": [ { "name": "GETNET", "display_name": "Getnet", "description": "Getnet is a high-tech global payment platform that helps businesses accept payments securely while providing the best frictionless experience for customers everywhere.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "Interac", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay", "RuPay", "Maestro" ], "supported_countries": [ "FIN", "BEL", "SWE", "IRL", "ESP", "NLD", "ARG", "NOR", "ARE", "POL", "MEX", "BRA", "ITA", "GBR", "CHE", "AUT", "DNK", "IND", "PRT", "CHL", "URY", "LUX", "FRA", "DEU" ], "supported_currencies": [ "ARS", "UYU", "EUR", "SEK", "NOK", "CHF", "INR", "AED", "MXN", "PLN", "DKK", "CLP", "BRL", "GBP" ] } ], "supported_webhook_flows": [ "payments", "refunds" ] }, { "name": "HIPAY", "display_name": "Hipay", "description": "HiPay is an independent global payment service provider that is based in France.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "Interac", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay" ], "supported_countries": [ "ZAF", "SWE", "CAN", "JPN", "HKG", "NOR", "CZE", "POL", "DNK", "USA", "GBR", "AUS", "CHE" ], "supported_currencies": [ "EUR", "GBP", "NOK", "HKD", "AUD", "ZAR", "CHF", "SEK", "DKK", "PLN", "CZK", "USD", "CAD", "JPY" ] }, { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "Interac", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay" ], "supported_countries": [ "AUS", "USA", "CAN", "CZE", "POL", "SWE", "GBR", "NOR", "ZAF", "DNK", "CHE", "JPN", "HKG" ], "supported_currencies": [ "HKD", "DKK", "SEK", "PLN", "GBP", "CAD", "CZK", "JPY", "USD", "EUR", "AUD", "NOK", "CHF", "ZAR" ] } ], "supported_webhook_flows": [] }, { "name": "KLARNA", "display_name": "Klarna", "description": "Klarna provides payment processing services for the e-commerce industry, managing store claims and customer payments.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "pay_later", "payment_method_type": "klarna", "payment_method_type_display_name": "Klarna", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "GRC", "PRT", "ESP", "CHE", "SWE", "CZE", "IRL", "FIN", "USA", "GBR", "NZL", "POL", "DNK", "NLD", "BEL", "NOR", "CAN", "AUS", "ITA", "DEU", "FRA", "AUT" ], "supported_currencies": [ "PLN", "CZK", "NOK", "CHF", "CAD", "AUD", "NZD", "DKK", "GBP", "SEK", "EUR", "USD" ] } ], "supported_webhook_flows": [] }, { "name": "MONERIS", "display_name": "Moneris", "description": "Moneris is Canada's top payment solutions provider, empowering businesses with innovative mobile, online & in-store solutions.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "Interac", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay" ], "supported_countries": [ "VUT", "SGP", "HUN", "DOM", "TUN", "LAO", "THA", "WSM", "PRY", "SLV", "BDI", "SVN", "KAZ", "TZA", "ESP", "TUR", "SLE", "BLZ", "MDA", "SWE", "BMU", "AGO", "ISR", "PRT", "BGR", "KWT", "DEU", "JOR", "SYC", "MRT", "BGD", "IDN", "CHL", "LUX", "GRC", "RWA", "VNM", "BIH", "SHN", "UGA", "HRV", "SRB", "CHE", "MDV", "FIN", "PER", "KEN", "BTN", "GIN", "ROU", "NIC", "KOR", "NAM", "COM", "CUB", "LVA", "DJI", "ZAF", "SLB", "ARE", "AUT", "MDG", "ITA", "GBR", "SAU", "LKA", "BHR", "RUS", "ZMB", "BRB", "NZL", "LSO", "MAC", "LBR", "HND", "PNG", "PAK", "USA", "GTM", "TKM", "AZE", "CRI", "POL", "BEL", "TJK", "AUS", "BRA", "UZB", "QAT", "EGY", "MWI", "CYM", "NOR", "ALB", "AFG", "DZA", "MEX", "DNK", "HKG", "MYS", "GUY", "FRA", "SWZ", "BLR", "JPN", "BRN", "NGA", "IND", "SVK", "LTU", "TWN", "MAR", "JAM", "BOL", "CZE", "EST", "TTO", "CYP", "COL", "ISL", "IRL", "GEO", "URY", "ABW", "MLT", "MKD", "GIB", "FJI", "CHN", "NLD", "OMN", "HTI", "NPL", "SUR", "GMB", "CPV", "ARG", "MOZ", "MUS" ], "supported_currencies": [ "PGK", "ZAR", "LSL", "MGA", "MWK", "AZN", "BIF", "NGN", "NIO", "JOD", "KWD", "NOK", "MYR", "HUF", "NAD", "AFN", "SBD", "INR", "BBD", "GTQ", "RUB", "GMD", "WST", "ALL", "MXN", "RON", "BYN", "MAD", "OMR", "HRK", "BAM", "HTG", "RSD", "BDT", "TMT", "CHF", "AUD", "AWG", "AED", "TTD", "QAR", "BND", "SEK", "TND", "DZD", "RWF", "BOB", "JMD", "XPF", "NZD", "VUV", "UZS", "PYG", "ARS", "TJS", "AOA", "MOP", "UGX", "DOP", "SLL", "BRL", "KYD", "THB", "FJD", "BZD", "KMF", "MKD", "UYU", "XOF", "DKK", "PHP", "SHP", "SGD", "BTN", "MUR", "SCR", "XCD", "ZMW", "JPY", "PEN", "ANG", "HKD", "KES", "LAK", "SZL", "CRC", "PLN", "CNY", "SVC", "IDR", "MDL", "USD", "VND", "BMD", "DJF", "GEL", "KRW", "KZT", "NPR", "PKR", "CUP", "MRU", "CZK", "ILS", "GYD", "LKR", "LRD", "BGN", "GIP", "TZS", "EUR", "GBP", "MZN", "BHD", "MVR", "SAR", "TWD", "COP", "GNF", "SRD", "TRY", "HNL", "EGP", "ISK", "CLP", "CVE" ] }, { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "Interac", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay" ], "supported_countries": [ "RWA", "MDV", "ISL", "FIN", "PRT", "COM", "USA", "UZB", "POL", "LAO", "SVK", "UGA", "BRN", "DOM", "MDA", "COL", "CRI", "BEL", "TKM", "KWT", "BGR", "MAR", "CHL", "SWE", "TWN", "JOR", "AUS", "MUS", "ARE", "KOR", "LUX", "SLV", "GRC", "URY", "LBR", "AUT", "HTI", "EST", "DEU", "ABW", "MAC", "MLT", "SLE", "OMN", "HND", "DJI", "AFG", "MYS", "THA", "SYC", "NIC", "GMB", "VUT", "PAK", "IND", "MOZ", "ROU", "JPN", "MKD", "ZAF", "BLR", "HKG", "LSO", "BDI", "PNG", "DNK", "EGY", "LKA", "ARG", "PRY", "BRA", "HRV", "JAM", "NOR", "IRL", "GIN", "BIH", "MEX", "BMU", "ITA", "WSM", "BRB", "BOL", "TJK", "FJI", "TUR", "NLD", "HUN", "CYP", "SAU", "ZMB", "ESP", "GEO", "RUS", "MDG", "DZA", "TTO", "AGO", "GTM", "SGP", "CYM", "GIB", "SVN", "FRA", "GUY", "MWI", "QAT", "LTU", "PER", "SWZ", "VNM", "LVA", "AZE", "BHR", "ISR", "CUB", "GBR", "BLZ", "CZE", "SLB", "MRT", "NGA", "BGD", "CHN", "SUR", "KEN", "ALB", "TUN", "SHN", "CHE", "BTN", "NZL", "KAZ", "NAM", "TZA", "CPV", "IDN", "SRB", "NPL" ], "supported_currencies": [ "DOP", "ISK", "AUD", "BMD", "SBD", "XOF", "AFN", "RWF", "PGK", "UZS", "HRK", "LAK", "BBD", "CVE", "MZN", "CLP", "MUR", "GBP", "BHD", "JPY", "ALL", "KMF", "NZD", "QAR", "BZD", "GYD", "TJS", "NIO", "LKR", "LRD", "MKD", "PKR", "XCD", "MXN", "TMT", "USD", "SHP", "VND", "NOK", "GIP", "MYR", "BYN", "KZT", "BAM", "BDT", "BGN", "EUR", "NPR", "PHP", "ZAR", "XPF", "SLL", "BND", "CRC", "JOD", "RON", "WST", "SZL", "GNF", "TWD", "KES", "MOP", "JMD", "TZS", "GTQ", "CZK", "INR", "SCR", "GMD", "TRY", "HTG", "NGN", "MDL", "OMR", "KYD", "SGD", "HNL", "AED", "AWG", "SRD", "VUV", "CNY", "THB", "RUB", "SEK", "CHF", "KWD", "BIF", "BOB", "PLN", "MGA", "SAR", "TND", "PYG", "SVC", "TTD", "UGX", "ANG", "DJF", "DKK", "EGP", "DZD", "ZMW", "BRL", "AOA", "AZN", "IDR", "FJD", "MWK", "MRU", "GEL", "ARS", "HUF", "ILS", "MVR", "UYU", "MAD", "HKD", "LSL", "PEN", "NAD", "CUP", "KRW", "COP", "BTN", "RSD" ] } ], "supported_webhook_flows": [] }, { "name": "OPENNODE", "display_name": "Opennode", "description": "OpenNode offers accessible way for e-commerce businesses to process bitcoin payments.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_method_type_display_name": "Crypto", "mandates": "not_supported", "refunds": "not_supported", "supported_capture_methods": [ "automatic" ], "supported_countries": [ "SVN", "PHL", "CAN", "AUS", "BEL", "MEX", "NLD", "FIN", "GBR", "MLT", "ESP", "USA", "EST", "PRT", "SVK", "JPN", "CYP", "LVA", "LTU", "ZAF", "BRA", "HRV", "DEU", "GRC", "ITA", "SGP", "FRA", "LUX", "IRL", "NZL", "AUT" ], "supported_currencies": [ "AUD", "JPY", "BRL", "CAD", "USD", "MXN", "PHP", "GBP", "EUR", "ZAR", "SGD", "NZD" ] } ], "supported_webhook_flows": [ "payments" ] } ] } ``` ## 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.113.0
7b3c33c81c8f896847a3a0bb0ead90a6a67f8e61
7b3c33c81c8f896847a3a0bb0ead90a6a67f8e61
juspay/hyperswitch
juspay__hyperswitch-7850
Bug: Update Postman Assertions for Payments API Responses for `Stripe` - `Sofort` `Sofort` Bank Redirect using `Stripe` has been deprecated, which fails Postman Test Cases for the same.
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json index f529af7b066..db5ff59100b 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json @@ -19,22 +19,21 @@ "Scenario13-BNPL-afterpay", "Scenario14-BNPL-affirm", "Scenario15-Bank Redirect-Ideal", - "Scenario16-Bank Redirect-sofort", - "Scenario17-Bank Redirect-eps", - "Scenario18-Bank Transfer-ach", - "Scenario19-Bank Debit-ach", - "Scenario20-Wallet-Wechatpay", - "Scenario21- Update address and List Payment method", - "Scenario22- Update Amount", - "Scenario23-Add card flow", - "Scenario24-Don't Pass CVV for save card flow and verifysuccess payment", - "Scenario25-Save card payment with manual capture", - "Scenario26-Create payment without customer_id and with billing address and shipping address", - "Scenario27-Confirm a payment with requires_customer_action status", - "Scenario28-Create payment with payment method billing", - "Scenario29-Update payment with payment method billing", - "Scenario30-Pass payment method billing in Confirm", - "Scenario31-Ensure API Contract for Payment Method Data", - "Scenario32-Check is payment checks are populated" + "Scenario16-Bank Redirect-eps", + "Scenario17-Bank Transfer-ach", + "Scenario18-Bank Debit-ach", + "Scenario19-Wallet-Wechatpay", + "Scenario20- Update address and List Payment method", + "Scenario21- Update Amount", + "Scenario22-Add card flow", + "Scenario23-Don't Pass CVV for save card flow and verifysuccess payment", + "Scenario24-Save card payment with manual capture", + "Scenario25-Create payment without customer_id and with billing address and shipping address", + "Scenario26-Confirm a payment with requires_customer_action status", + "Scenario27-Create payment with payment method billing", + "Scenario28-Update payment with payment method billing", + "Scenario29-Pass payment method billing in Confirm", + "Scenario30-Ensure API Contract for Payment Method Data", + "Scenario31-Check is payment checks are populated" ] } \ No newline at end of file diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-eps/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js deleted file mode 100644 index c2e29faee5a..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js +++ /dev/null @@ -1,123 +0,0 @@ -// Validate status 2xx -pm.test("[POST]::/payments/:id/confirm - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test( - "[POST]::/payments/:id/confirm - Content-Type is application/json", - function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include( - "application/json", - ); - }, -); - -// Validate if response has JSON Body -pm.test("[POST]::/payments/:id/confirm - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - -// Set response object as internal variable -let jsonData = {}; -try { - jsonData = pm.response.json(); -} catch (e) {} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log( - "- use {{payment_id}} as collection variable for value", - jsonData.payment_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", - ); -} - -// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id -if (jsonData?.mandate_id) { - pm.collectionVariables.set("mandate_id", jsonData.mandate_id); - console.log( - "- use {{mandate_id}} as collection variable for value", - jsonData.mandate_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", - ); -} - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log( - "- use {{client_secret}} as collection variable for value", - jsonData.client_secret, - ); -} else { - console.log( - "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", - ); -} - -// Response body should have value "failed" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'failed'", - function () { - pm.expect(jsonData.status).to.eql("failed"); - }, - ); -} - -// Response body should have "next_action" -pm.test( - "[POST]::/payments - Content check if 'next_action' exists", - function () { - pm.expect(typeof jsonData.next_action !== "undefined").to.be - .true; - }, -); - -// Response body should have value "sofort" for "payment_method_type" -if (jsonData?.payment_method_type) { - pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'sofort'", - function () { - pm.expect(jsonData.payment_method_type).to.eql("sofort"); - }, - ); -} - -// Response body should have value "payment_method_not_available" for "error_code" -if (jsonData?.error_code) { - pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'payment_method_not_available'", - function () { - pm.expect(jsonData.error_code).to.eql("payment_method_not_available"); - }, - ); -} - -// Response body should have value "Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort" for "error_message" -if (jsonData?.error_message) { - pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort'", - function () { - pm.expect(jsonData.error_message).to.eql("Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort"); - }, - ); -} - -// Response body should have value "stripe" for "connector" -if (jsonData?.connector) { - pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'", - function () { - pm.expect(jsonData.connector).to.eql("stripe"); - }, - ); -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/request.json deleted file mode 100644 index 686ac64b607..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/request.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{publishable_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "payment_method": "bank_redirect", - "payment_method_type": "sofort", - "payment_method_data": { - "bank_redirect": { - "sofort": { - "bank_name": "hypo_noe_lb_fur_niederosterreich_u_wien", - "preferred_language": "en" - } - } - }, - "client_secret": "{{client_secret}}" - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/confirm", - "host": ["{{baseUrl}}"], - "path": ["payments", ":id", "confirm"], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API" -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/request.json deleted file mode 100644 index 0b0c56d2660..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Create/request.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "amount": 1000, - "currency": "EUR", - "confirm": false, - "capture_method": "automatic", - "capture_on": "2022-09-10T10:11:12Z", - "amount_to_capture": 1000, - "customer_id": "StripeCustomer", - "email": "[email protected]", - "name": "John Doe", - "phone": "999999999", - "phone_country_code": "+65", - "description": "Its my first payment request", - "authentication_type": "three_ds", - "return_url": "https://duck.com", - "billing": { - "address": { - "first_name": "John", - "last_name": "Doe", - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "DE" - } - }, - "browser_info": { - "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", - "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", - "language": "nl-NL", - "color_depth": 24, - "screen_height": 723, - "screen_width": 1536, - "time_zone": 0, - "java_enabled": true, - "java_script_enabled": true, - "ip_address": "127.0.0.1" - }, - "shipping": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "US", - "first_name": "John", - "last_name": "Doe" - } - }, - "statement_descriptor_name": "joseph", - "statement_descriptor_suffix": "JS", - "metadata": { - "udf1": "value1", - "new_customer": "true", - "login_date": "2019-09-10T10:11:12Z" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": ["{{baseUrl}}"], - "path": ["payments"] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js deleted file mode 100644 index e99ef624bf2..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js +++ /dev/null @@ -1,91 +0,0 @@ -// Validate status 2xx -pm.test("[GET]::/payments/:id - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[GET]::/payments/:id - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include( - "application/json", - ); -}); - -// Validate if response has JSON Body -pm.test("[GET]::/payments/:id - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - -// Set response object as internal variable -let jsonData = {}; -try { - jsonData = pm.response.json(); -} catch (e) {} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log( - "- use {{payment_id}} as collection variable for value", - jsonData.payment_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", - ); -} - -// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id -if (jsonData?.mandate_id) { - pm.collectionVariables.set("mandate_id", jsonData.mandate_id); - console.log( - "- use {{mandate_id}} as collection variable for value", - jsonData.mandate_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", - ); -} - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log( - "- use {{client_secret}} as collection variable for value", - jsonData.client_secret, - ); -} else { - console.log( - "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", - ); -} - -// Response body should have value "failed" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments:id - Content check if value for 'status' matches 'failed'", - function () { - pm.expect(jsonData.status).to.eql("failed"); - }, - ); -} - -// Response body should have value "payment_method_not_available" for "error_code" -if (jsonData?.error_code) { - pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'payment_method_not_available'", - function () { - pm.expect(jsonData.error_code).to.eql("payment_method_not_available"); - }, - ); -} - -// Response body should have value "Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort" for "error_message" -if (jsonData?.error_message) { - pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort'", - function () { - pm.expect(jsonData.error_message).to.eql("Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort"); - }, - ); -} \ No newline at end of file diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Transfer-ach/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/event.prerequest.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Debit-ach/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/.event.meta.json deleted file mode 100644 index 220b1a6723d..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Confirm/.event.meta.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "eventOrder": ["event.test.js", "event.prerequest.js"] -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/event.prerequest.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Bank Debit-ach/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario19-Wallet-Wechatpay/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant-copy/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/List Payment Methods for a Merchant/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant-copy/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/List Payment Methods for a Merchant/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20- Update address and List Payment method/Payments - Update/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update address and List Payment method/Payments - Update/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario21- Update Amount/Payments - Update/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/List payment methods for a Customer/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update Amount/Payments - Update/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/List payment methods for a Customer/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Create Copy/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Refunds - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Create Copy/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22-Add card flow/Save card payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Refunds - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Add card flow/Save card payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/List payment methods for a Customer/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/List payment methods for a Customer/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Capture/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Don't Pass CVV for save card flow and verifysuccess payment/Save card payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/List payment methods for a Customer/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve-copy/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Capture/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Create Copy/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve-copy/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Refunds - Retrieve Copy/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Create Copy/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario24-Save card payment with manual capture/Save card payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Refunds - Retrieve Copy/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario25-Save card payment with manual capture/Save card payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario26-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario18-Bank Transfer-ach/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Confirm/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Create payment with payment method billing/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario27-Confirm a payment with requires_customer_action status/Payments - Create with confirm true/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Create payment with payment method billing/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario28-Update payment with payment method billing/Payments - Update/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Create/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Confirm/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/event.prerequest.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario20-Wallet-Wechatpay/Payments - Create/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Create/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/response.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Pass payment method billing in Confirm/Payments - Retrieve/response.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/.event.meta.json deleted file mode 100644 index 0731450e6b2..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/.event.meta.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "eventOrder": ["event.test.js"] -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/request.json deleted file mode 100644 index 6cd4b7d96c5..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Retrieve/request.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id?force_sync=true", - "host": ["{{baseUrl}}"], - "path": ["payments", ":id"], - "query": [ - { - "key": "force_sync", - "value": "true" - } - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/.event.meta.json deleted file mode 100644 index 0731450e6b2..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Update payment with payment method billing/Payments - Update/.event.meta.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "eventOrder": ["event.test.js"] -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/.meta.json deleted file mode 100644 index 57d3f8e2bc7..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/.meta.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "childrenOrder": [ - "Payments - Create", - "Payments - Confirm", - "Payments - Retrieve" - ] -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Confirm/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/event.prerequest.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/event.prerequest.js deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/event.test.js deleted file mode 100644 index 0444324000a..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/event.test.js +++ /dev/null @@ -1,71 +0,0 @@ -// Validate status 2xx -pm.test("[POST]::/payments - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[POST]::/payments - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include( - "application/json", - ); -}); - -// Validate if response has JSON Body -pm.test("[POST]::/payments - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - -// Set response object as internal variable -let jsonData = {}; -try { - jsonData = pm.response.json(); -} catch (e) {} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log( - "- use {{payment_id}} as collection variable for value", - jsonData.payment_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", - ); -} - -// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id -if (jsonData?.mandate_id) { - pm.collectionVariables.set("mandate_id", jsonData.mandate_id); - console.log( - "- use {{mandate_id}} as collection variable for value", - jsonData.mandate_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", - ); -} - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log( - "- use {{client_secret}} as collection variable for value", - jsonData.client_secret, - ); -} else { - console.log( - "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", - ); -} - -// Response body should have value "requires_payment_method" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'", - function () { - pm.expect(jsonData.status).to.eql("requires_payment_method"); - }, - ); -} diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/response.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario30-Pass payment method billing in Confirm/Payments - Retrieve/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - cvv check fails/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - cvv check fails/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - cvv check fails/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - cvv check fails/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - cvv check fails/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - cvv check fails/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - cvv check fails/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - payment check populated for successful payment without billing/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - postal code check fail/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - postal code check fail/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - postal code check fail/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - postal code check fail/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - postal code check fail/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - postal code check fail/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - postal code check fail/request.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - successful payment with billing/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/.event.meta.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - successful payment with billing/.event.meta.json diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - successful payment with billing/event.test.js similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/event.test.js rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - successful payment with billing/event.test.js diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - successful payment with billing/request.json similarity index 100% rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Check is payment checks are populated/Payments - successful payment with billing/request.json rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario31-Check is payment checks are populated/Payments - successful payment with billing/request.json
2025-04-17T18:42:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> ### Summary of Changes Simply, Removed the Sofort TestCase for Stripe, nothing else. And, because of this had to make some name changes. _And the Errors showing up in the Screenshot labelled as After is not due to this PR_ ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The Postman Test Cases for `Sofort` using `Stripe` are failing because `Sofort` has been deprecated. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **Before** <img width="1058" alt="image" src="https://github.com/user-attachments/assets/4aa5f40d-6ce1-4c08-a807-e985816237f6" /> **After** <!-- img width="493" alt="image" src="https://github.com/user-attachments/assets/63c6dbf8-d1ec-4770-8743-10dbc9a8259d" / --> ![image](https://github.com/user-attachments/assets/dd26e322-d6c5-4f56-90ff-a768eb7e7813) ## 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.113.0
69ba651abd13de76e603dab8bbc56c5f3ee2176c
69ba651abd13de76e603dab8bbc56c5f3ee2176c
juspay/hyperswitch
juspay__hyperswitch-7844
Bug: Last used merchant account context To enhance the user experience, especially during sign-up or when switching between multiple merchant accounts, we can store the last used merchant account context directly in the users table. This allows the system to automatically restore the previously active context when a user logs in or returns to the dashboard, rather than requiring them to manually select a merchant account each time.
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 4f681cda25b..649b8820859 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -41,3 +41,6 @@ pub const REDIS_SSO_TTL: i64 = 5 * 60; // 5 minutes pub const DEFAULT_PROFILE_NAME: &str = "default"; pub const DEFAULT_PRODUCT_TYPE: common_enums::MerchantProductType = common_enums::MerchantProductType::Orchestration; + +pub const LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS: i64 = 60 * 60 * 24 * 7; // 7 days +pub const LINEAGE_CONTEXT_PREFIX: &str = "LINEAGE_CONTEXT_"; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 91b20621da8..6e5360d8848 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -3169,6 +3169,23 @@ pub async fn switch_org_for_user( } }; + let lineage_context = domain::LineageContext { + user_id: user_from_token.user_id.clone(), + merchant_id: merchant_id.clone(), + role_id: role_id.clone(), + org_id: request.org_id.clone(), + profile_id: profile_id.clone(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id) + .clone(), + }; + + lineage_context + .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) + .await; + let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, @@ -3364,6 +3381,23 @@ pub async fn switch_merchant_for_user_in_org( } }; + let lineage_context = domain::LineageContext { + user_id: user_from_token.user_id.clone(), + merchant_id: merchant_id.clone(), + role_id: role_id.clone(), + org_id: org_id.clone(), + profile_id: profile_id.clone(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id) + .clone(), + }; + + lineage_context + .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) + .await; + let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, @@ -3480,6 +3514,23 @@ pub async fn switch_profile_for_user_in_org_and_merchant( } }; + let lineage_context = domain::LineageContext { + user_id: user_from_token.user_id.clone(), + merchant_id: user_from_token.merchant_id.clone(), + role_id: role_id.clone(), + org_id: user_from_token.org_id.clone(), + profile_id: profile_id.clone(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id) + .clone(), + }; + + lineage_context + .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) + .await; + let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 8bf177035ef..016995cb550 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -23,7 +23,7 @@ use hyperswitch_domain_models::api::ApplicationResponse; use masking::{ExposeInterface, PeekInterface, Secret}; use once_cell::sync::Lazy; use rand::distributions::{Alphanumeric, DistString}; -use router_env::env; +use router_env::{env, logger}; use time::PrimitiveDateTime; use unicode_segmentation::UnicodeSegmentation; #[cfg(feature = "keymanager_create")] @@ -39,7 +39,7 @@ use crate::{ routes::SessionState, services::{self, authentication::UserFromToken}, types::{domain, transformers::ForeignFrom}, - utils::user::password, + utils::{self, user::password}, }; pub mod dashboard_metadata; @@ -1458,3 +1458,54 @@ where .change_context(UserErrors::InternalServerError) } } + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct LineageContext { + pub user_id: String, + pub merchant_id: id_type::MerchantId, + pub role_id: String, + pub org_id: id_type::OrganizationId, + pub profile_id: id_type::ProfileId, + pub tenant_id: id_type::TenantId, +} + +impl LineageContext { + pub async fn try_get_lineage_context_from_cache( + state: &SessionState, + user_id: &str, + ) -> Option<Self> { + // The errors are not handled here because we don't want to fail the request if the cache operation fails. + // The errors are logged for debugging purposes. + match utils::user::get_lineage_context_from_cache(state, user_id).await { + Ok(Some(ctx)) => Some(ctx), + Ok(None) => { + logger::debug!("Lineage context not found in Redis for user {}", user_id); + None + } + Err(e) => { + logger::error!( + "Failed to retrieve lineage context from Redis for user {}: {:?}", + user_id, + e + ); + None + } + } + } + + pub async fn try_set_lineage_context_in_cache(&self, state: &SessionState, user_id: &str) { + // The errors are not handled here because we don't want to fail the request if the cache operation fails. + // The errors are logged for debugging purposes. + if let Err(e) = + utils::user::set_lineage_context_in_cache(state, user_id, self.clone()).await + { + logger::error!( + "Failed to set lineage context in Redis for user {}: {:?}", + user_id, + e + ); + } else { + logger::debug!("Lineage context cached for user {}", user_id); + } + } +} diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index bf5556dd9a7..0214d3cdd15 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -1,6 +1,9 @@ use common_enums::TokenPurpose; use common_utils::id_type; -use diesel_models::{enums::UserStatus, user_role::UserRole}; +use diesel_models::{ + enums::{UserRoleVersion, UserStatus}, + user_role::UserRole, +}; use error_stack::ResultExt; use masking::Secret; @@ -10,6 +13,7 @@ use crate::{ db::user_role::ListUserRolesByUserIdPayload, routes::SessionState, services::authentication as auth, + types::domain::LineageContext, utils, }; @@ -124,23 +128,93 @@ impl JWTFlow { next_flow: &NextFlow, user_role: &UserRole, ) -> UserResult<Secret<String>> { + let user_id = next_flow.user.get_user_id(); + let cached_lineage_context = + LineageContext::try_get_lineage_context_from_cache(state, user_id).await; + + let new_lineage_context = match cached_lineage_context { + Some(ctx) => { + let tenant_id = ctx.tenant_id.clone(); + let user_role_match_v1 = state + .global_store + .find_user_role_by_user_id_and_lineage( + &ctx.user_id, + &tenant_id, + &ctx.org_id, + &ctx.merchant_id, + &ctx.profile_id, + UserRoleVersion::V1, + ) + .await + .is_ok(); + + if user_role_match_v1 { + ctx + } else { + let user_role_match_v2 = state + .global_store + .find_user_role_by_user_id_and_lineage( + &ctx.user_id, + &tenant_id, + &ctx.org_id, + &ctx.merchant_id, + &ctx.profile_id, + UserRoleVersion::V2, + ) + .await + .is_ok(); + + if user_role_match_v2 { + ctx + } else { + // fallback to default lineage if cached context is invalid + Self::resolve_lineage_from_user_role(state, user_role, user_id).await? + } + } + } + None => + // no cached context found + { + Self::resolve_lineage_from_user_role(state, user_role, user_id).await? + } + }; + + new_lineage_context + .try_set_lineage_context_in_cache(state, user_id) + .await; + + auth::AuthToken::new_token( + new_lineage_context.user_id, + new_lineage_context.merchant_id, + new_lineage_context.role_id, + &state.conf, + new_lineage_context.org_id, + new_lineage_context.profile_id, + Some(new_lineage_context.tenant_id), + ) + .await + .map(|token| token.into()) + } + + pub async fn resolve_lineage_from_user_role( + state: &SessionState, + user_role: &UserRole, + user_id: &str, + ) -> UserResult<LineageContext> { let org_id = utils::user_role::get_single_org_id(state, user_role).await?; let merchant_id = utils::user_role::get_single_merchant_id(state, user_role, &org_id).await?; let profile_id = utils::user_role::get_single_profile_id(state, user_role, &merchant_id).await?; - auth::AuthToken::new_token( - next_flow.user.get_user_id().to_string(), - merchant_id, - user_role.role_id.clone(), - &state.conf, + Ok(LineageContext { + user_id: user_id.to_string(), org_id, + merchant_id, profile_id, - Some(user_role.tenant_id.clone()), - ) - .await - .map(|token| token.into()) + role_id: user_role.role_id.clone(), + tenant_id: user_role.tenant_id.clone(), + }) } } diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 89612fc1892..3e339a2a570 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -12,7 +12,10 @@ use redis_interface::RedisConnectionPool; use router_env::env; use crate::{ - consts::user::{REDIS_SSO_PREFIX, REDIS_SSO_TTL}, + consts::user::{ + LINEAGE_CONTEXT_PREFIX, LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS, REDIS_SSO_PREFIX, + REDIS_SSO_TTL, + }, core::errors::{StorageError, UserErrors, UserResult}, routes::SessionState, services::{ @@ -20,7 +23,7 @@ use crate::{ authorization::roles::RoleInfo, }, types::{ - domain::{self, MerchantAccount, UserFromStorage}, + domain::{self, LineageContext, MerchantAccount, UserFromStorage}, transformers::ForeignFrom, }, }; @@ -339,3 +342,49 @@ pub async fn validate_email_domain_auth_type_using_db( .then_some(()) .ok_or(UserErrors::InvalidUserAuthMethodOperation.into()) } + +pub async fn get_lineage_context_from_cache( + state: &SessionState, + user_id: &str, +) -> UserResult<Option<LineageContext>> { + let connection = get_redis_connection(state)?; + let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); + let lineage_context = connection + .get_key::<Option<String>>(&key.into()) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get lineage context from redis")?; + + match lineage_context { + Some(json_str) => { + let ctx = serde_json::from_str::<LineageContext>(&json_str) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to deserialize LineageContext from JSON")?; + Ok(Some(ctx)) + } + None => Ok(None), + } +} + +pub async fn set_lineage_context_in_cache( + state: &SessionState, + user_id: &str, + lineage_context: LineageContext, +) -> UserResult<()> { + let connection = get_redis_connection(state)?; + let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); + let serialized_lineage_context: String = serde_json::to_string(&lineage_context) + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to serialize LineageContext")?; + connection + .set_key_with_expiry( + &key.into(), + serialized_lineage_context, + LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to set lineage context in redis")?; + + Ok(()) +}
2025-04-22T14:54:00Z
## 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 lineage context caching to enhance login and account-switch flows with better continuity and reduced DB load. ### Key Changes - **During Login:** - Attempt to fetch the last used `LineageContext` from Redis (`LINEAGE_CONTEXT_<user_id>`). - If context is found: - Validate whether a matching user role exists (using both `V1` and `V2` role versions). - If a valid user_role is found → use this lineage context to issue the JWT token. - If not → fallback to the default user_role-based resolution logic. - If context is **not found in cache**, fallback to the existing login flow entirely. - **During Account Switch:** - After switching org/merchant/profile context and issuing the new JWT token, the new `LineageContext` is saved to Redis (`LINEAGE_CONTEXT_<user_id>`). - This allows restoring the last used org/merchant/profile on future logins. - **Redis Cache Expiry:** - Cached lineage context entries are stored with a TTL of **7 days**. - If the user is inactive beyond this duration, the system reverts to default logic. ### 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). --> - Improves user experience by remembering their last used account context across sessions. - Reduces unnecessary DB lookups during login for returning users. - Ensures fallback safety in case of invalid or expired lineage context. ## 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 locally with TTL as 1 minute, keys are getting stored in redis <img width="1065" alt="Screenshot 2025-04-22 at 7 40 32 PM" src="https://github.com/user-attachments/assets/1201a92b-7957-4075-8ec6-9a75376c842a" /> <img width="1369" alt="image" src="https://github.com/user-attachments/assets/2e8fbec0-a1e1-4ef9-b280-67ccbea7b1d1" /> ![Screenshot 2025-04-22 at 7 41 43 PM](https://github.com/user-attachments/assets/b0cdf010-0828-4982-98a4-91625d707c84) ### Test 1: - Log in to the merchant account. - Check redis using the key: ```GET LINEAGE_CONTEXT_<user_id>``` The value should contain the last used lineage context for the user. - Switch to another org/merchant/profile. - Recheck redis with the same key: ```GET LINEAGE_CONTEXT_<user_id>```. The lineage should now be changed. ### Test 2: - After the above test, log out and log in back, within the TTL for the lineage_context, which is 7 days. - You should be logged in to exactly the same lineage which you last used. ### Test 3 (optional): - Have a note of the lineage. - Do not use this account for 7 days. - Try logging in now. - You should be logged in to a random account (possibly the lineage which you have not used last) - This proves, that the key has expired and the default fallback login is now used. ## 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.113.0
776bde00efce8be35e0c63c1bdc6215921babddf
776bde00efce8be35e0c63c1bdc6215921babddf
juspay/hyperswitch
juspay__hyperswitch-7843
Bug: Fix Cypress v2 Core Flows Test Failures The Cypress tests for v2 failed due to the recent authentication changes introduced in [PR #7487](https://github.com/juspay/hyperswitch/pull/7487) and payment method config changes.
diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js index 228dfd2cfdd..a645ec5c555 100644 --- a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js +++ b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js @@ -54,10 +54,10 @@ const multiUseMandateData = { export const payment_methods_enabled = [ { - payment_method: "bank_debit", - payment_method_types: [ + payment_method_type: "bank_debit", + payment_method_subtypes: [ { - payment_method_type: "ach", + payment_method_subtype: "ach", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -68,7 +68,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "bacs", + payment_method_subtype: "bacs", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -79,7 +79,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "becs", + payment_method_subtype: "becs", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -90,7 +90,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "sepa", + payment_method_subtype: "sepa", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -103,10 +103,10 @@ export const payment_methods_enabled = [ ], }, { - payment_method: "bank_redirect", - payment_method_types: [ + payment_method_type: "bank_redirect", + payment_method_subtypes: [ { - payment_method_type: "blik", + payment_method_subtype: "blik", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -117,7 +117,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "eps", + payment_method_subtype: "eps", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -128,7 +128,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "ideal", + payment_method_subtype: "ideal", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -139,7 +139,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "giropay", + payment_method_subtype: "giropay", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -150,7 +150,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "local_bank_redirect", + payment_method_subtype: "local_bank_redirect", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -161,7 +161,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "przelewy24", + payment_method_subtype: "przelewy24", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -172,7 +172,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "sofort", + payment_method_subtype: "sofort", payment_experience: null, card_networks: null, accepted_currencies: null, @@ -185,10 +185,10 @@ export const payment_methods_enabled = [ ], }, { - payment_method: "bank_transfer", - payment_method_types: [ + payment_method_type: "bank_transfer", + payment_method_subtypes: [ { - payment_method_type: "ach", + payment_method_subtype: "ach", payment_experience: "redirect_to_url", card_networks: null, accepted_currencies: null, @@ -199,7 +199,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "bacs", + payment_method_subtype: "bacs", payment_experience: "redirect_to_url", card_networks: null, accepted_currencies: null, @@ -210,14 +210,14 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "pix", + payment_method_subtype: "pix", minimum_amount: -1, maximum_amount: 68607706, recurring_enabled: false, installment_payment_enabled: true, }, { - payment_method_type: "sepa", + payment_method_subtype: "sepa", payment_experience: "redirect_to_url", card_networks: null, accepted_currencies: null, @@ -230,10 +230,10 @@ export const payment_methods_enabled = [ ], }, { - payment_method: "card", - payment_method_types: [ + payment_method_type: "card", + payment_method_subtypes: [ { - payment_method_type: "credit", + payment_method_subtype: "credit", card_networks: [ "AmericanExpress", "Discover", @@ -251,7 +251,7 @@ export const payment_methods_enabled = [ installment_payment_enabled: true, }, { - payment_method_type: "debit", + payment_method_subtype: "debit", card_networks: [ "AmericanExpress", "Discover", @@ -271,10 +271,10 @@ export const payment_methods_enabled = [ ], }, { - payment_method: "card_redirect", - payment_method_types: [ + payment_method_type: "card_redirect", + payment_method_subtypes: [ { - payment_method_type: "card_redirect", + payment_method_subtype: "card_redirect", payment_experience: "redirect_to_url", card_networks: null, accepted_currencies: null, @@ -287,10 +287,10 @@ export const payment_methods_enabled = [ ], }, { - payment_method: "real_time_payment", - payment_method_types: [ + payment_method_type: "real_time_payment", + payment_method_subtypes: [ { - payment_method_type: "duit_now", + payment_method_subtype: "duit_now", minimum_amount: 1, maximum_amount: 68607706, recurring_enabled: true, @@ -298,7 +298,7 @@ export const payment_methods_enabled = [ payment_experience: "redirect_to_url", }, { - payment_method_type: "fps", + payment_method_subtype: "fps", minimum_amount: 1, maximum_amount: 68607706, recurring_enabled: true, @@ -306,7 +306,7 @@ export const payment_methods_enabled = [ payment_experience: "redirect_to_url", }, { - payment_method_type: "prompt_pay", + payment_method_subtype: "prompt_pay", minimum_amount: 1, maximum_amount: 68607706, recurring_enabled: true, @@ -314,7 +314,7 @@ export const payment_methods_enabled = [ payment_experience: "redirect_to_url", }, { - payment_method_type: "viet_qr", + payment_method_subtype: "viet_qr", minimum_amount: 1, maximum_amount: 68607706, recurring_enabled: true, @@ -324,10 +324,10 @@ export const payment_methods_enabled = [ ], }, { - payment_method: "upi", - payment_method_types: [ + payment_method_type: "upi", + payment_method_subtypes: [ { - payment_method_type: "upi_collect", + payment_method_subtype: "upi_collect", minimum_amount: 1, maximum_amount: 68607706, recurring_enabled: true, @@ -335,7 +335,7 @@ export const payment_methods_enabled = [ payment_experience: "redirect_to_url", }, { - payment_method_type: "upi_intent", + payment_method_subtype: "upi_intent", minimum_amount: 1, maximum_amount: 68607706, recurring_enabled: true, diff --git a/cypress-tests-v2/cypress/support/commands.js b/cypress-tests-v2/cypress/support/commands.js index 33f8907ce3f..54e52495d67 100644 --- a/cypress-tests-v2/cypress/support/commands.js +++ b/cypress-tests-v2/cypress/support/commands.js @@ -55,7 +55,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, }, body: organizationCreateBody, failOnStatusCode: false, @@ -91,7 +91,7 @@ Cypress.Commands.add("organizationRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, }, failOnStatusCode: false, }).then((response) => { @@ -135,7 +135,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, }, body: organizationUpdateBody, failOnStatusCode: false, @@ -185,7 +185,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, "X-Organization-Id": organization_id, }, body: merchantAccountCreateBody, @@ -230,7 +230,7 @@ Cypress.Commands.add("merchantAccountRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, }, failOnStatusCode: false, }).then((response) => { @@ -274,7 +274,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, }, body: merchantAccountUpdateBody, failOnStatusCode: false, @@ -310,7 +310,7 @@ Cypress.Commands.add( "businessProfileCreateCall", (businessProfileCreateBody, globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("apiKey"); + const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const url = `${base_url}/v2/profiles`; @@ -324,7 +324,8 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, + "x-merchant-id": merchant_id, ...customHeaders, }, body: businessProfileCreateBody, @@ -353,7 +354,7 @@ Cypress.Commands.add( ); Cypress.Commands.add("businessProfileRetrieveCall", (globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("apiKey"); + const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId"); @@ -368,7 +369,7 @@ Cypress.Commands.add("businessProfileRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, failOnStatusCode: false, @@ -395,7 +396,7 @@ Cypress.Commands.add( "businessProfileUpdateCall", (businessProfileUpdateBody, globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("apiKey"); + const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId"); @@ -410,7 +411,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, body: businessProfileUpdateBody, @@ -460,6 +461,7 @@ Cypress.Commands.add( const customHeaders = { "x-merchant-id": merchant_id, + "x-profile-id": profile_id, }; // Update request body @@ -501,7 +503,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, body: mcaCreateBody, @@ -536,10 +538,12 @@ Cypress.Commands.add("mcaRetrieveCall", (globalState) => { const connector_name = globalState.get("connectorId"); const merchant_connector_id = globalState.get("merchantConnectorId"); const merchant_id = globalState.get("merchantId"); + const profile_id = globalState.get("profileId"); const url = `${base_url}/v2/connector-accounts/${merchant_connector_id}`; const customHeaders = { "x-merchant-id": merchant_id, + "x-profile-id": profile_id, }; cy.request({ @@ -547,7 +551,7 @@ Cypress.Commands.add("mcaRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, failOnStatusCode: false, @@ -607,7 +611,7 @@ Cypress.Commands.add( url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, body: mcaUpdateBody, @@ -667,7 +671,7 @@ Cypress.Commands.add("apiKeyCreateCall", (apiKeyCreateBody, globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, body: apiKeyCreateBody, @@ -714,7 +718,7 @@ Cypress.Commands.add("apiKeyRetrieveCall", (globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, failOnStatusCode: false, @@ -764,7 +768,7 @@ Cypress.Commands.add("apiKeyUpdateCall", (apiKeyUpdateBody, globalState) => { url: url, headers: { "Content-Type": "application/json", - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, ...customHeaders, }, body: apiKeyUpdateBody, @@ -1172,7 +1176,7 @@ Cypress.Commands.add("merchantAccountsListCall", (globalState) => { method: "GET", url: url, headers: { - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, "Content-Type": "application/json", }, failOnStatusCode: false, @@ -1214,7 +1218,7 @@ Cypress.Commands.add("businessProfilesListCall", (globalState) => { method: "GET", url: url, headers: { - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, "Content-Type": "application/json", ...customHeaders, }, @@ -1250,13 +1254,14 @@ Cypress.Commands.add("mcaListCall", (globalState, service_type) => { const customHeaders = { "x-merchant-id": merchant_id, + "x-profile-id": profile_id, }; cy.request({ method: "GET", url: url, headers: { - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, "Content-Type": "application/json", ...customHeaders, }, @@ -1318,7 +1323,7 @@ Cypress.Commands.add("apiKeysListCall", (globalState) => { method: "GET", url: url, headers: { - "api-key": api_key, + "Authorization": `admin-api-key=${api_key}`, "Content-Type": "application/json", ...customHeaders, },
2025-04-13T16:09:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> <details> <summary>Changes</summary> - Changed the Authorization in the `commands.js` because Authorization changes had been made recently. - Changed field names in `payment_methods_enabled` accordingly as accepted by v2 endpoints. </details> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The v2 Cypress Tests were failing due to the recent Authentication Changes in #7487. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **_Before_** <img width="715" alt="image" src="https://github.com/user-attachments/assets/70f6ccfe-8094-47f0-b70f-34cb66cccc86" /> **_After_** <img width="714" alt="image" src="https://github.com/user-attachments/assets/3b1c6591-3667-468f-aa9d-01e8e01eb835" /> ## 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.113.0
4f4e31db24652e72ce50745e9d64618c93c692bc
4f4e31db24652e72ce50745e9d64618c93c692bc
juspay/hyperswitch
juspay__hyperswitch-7838
Bug: Add hyperswitch-react-demo-app to docker-compose
diff --git a/docker-compose.yml b/docker-compose.yml index ca8434cf058..cc58c38e88a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -11,7 +11,12 @@ services: prestart-hook: image: curlimages/curl-base:latest container_name: prestart-hook - entrypoint: ["/bin/sh", "-c", "apk add --no-cache bash && /bin/bash /prestart_hook.sh"] + entrypoint: + [ + "/bin/sh", + "-c", + "apk add --no-cache bash && /bin/bash /prestart_hook.sh", + ] volumes: - ./scripts/prestart_hook.sh:/prestart_hook.sh networks: @@ -60,7 +65,7 @@ services: environment: # format -> postgresql://DB_USER:DB_PASSWORD@HOST:PORT/DATABASE_NAME - DATABASE_URL=postgresql://db_user:db_pass@pg:5432/hyperswitch_db - + mailhog: image: mailhog/mailhog networks: @@ -100,13 +105,18 @@ services: container_name: poststart-hook depends_on: hyperswitch-server: - condition: service_healthy # Ensures it only starts when `hyperswitch-server` is healthy - entrypoint: ["/bin/sh", "-c", "apk add --no-cache bash jq && /bin/bash /poststart_hook.sh"] + condition: service_healthy # Ensures it only starts when `hyperswitch-server` is healthy + entrypoint: + [ + "/bin/sh", + "-c", + "apk add --no-cache bash jq && /bin/bash /poststart_hook.sh", + ] volumes: - ./scripts/poststart_hook.sh:/poststart_hook.sh networks: - - router_net - + - router_net + hyperswitch-producer: image: docker.juspay.io/juspaydotin/hyperswitch-producer:standalone pull_policy: always @@ -174,20 +184,13 @@ services: pull_policy: always ports: - "9050:9050" - - "9060:9060" - - "5252:5252" networks: - router_net depends_on: hyperswitch-server: condition: service_healthy environment: - - HYPERSWITCH_PUBLISHABLE_KEY=placeholder_publishable_key - - HYPERSWITCH_SECRET_KEY=placeholder_api_key - - HYPERSWITCH_SERVER_URL=http://localhost:8080 - - HYPERSWITCH_SERVER_URL_FOR_DEMO_APP=http://hyperswitch-server:8080 - - HYPERSWITCH_CLIENT_URL=http://localhost:9050 - - SELF_SERVER_URL=http://localhost:5252 + - ENABLE_LOGGING=true - SDK_ENV=local - ENV_LOGGING_URL=http://localhost:3103 - ENV_BACKEND_URL=http://localhost:8080 @@ -442,3 +445,25 @@ services: volumes: - ./config/vector.yaml:/etc/vector/vector.yaml - /var/run/docker.sock:/var/run/docker.sock + + hyperswitch-demo: + image: docker.juspay.io/juspaydotin/hyperswitch-react-demo-app:latest + pull_policy: always + ports: + - "9060:9060" + - "5252:5252" + networks: + - router_net + depends_on: + hyperswitch-server: + condition: service_healthy + hyperswitch-web: + condition: service_healthy + environment: + - HYPERSWITCH_PUBLISHABLE_KEY=placeholder_publishable_key + - HYPERSWITCH_SECRET_KEY=placeholder_api_key + - PROFILE_ID=placeholder_profile_id + - HYPERSWITCH_CLIENT_URL=http://localhost:9050 + - HYPERSWITCH_SERVER_URL=http://localhost:8080 + labels: + logs: "promtail"
2025-04-17T08:35:03Z
## Type of Change - [x] Enhancement ## Description Added `hyperswitch-demo` to the Docker Compose setup to provide a visual interface for the SDK. ## Motivation and Context This addition enables merchants to preview and interact with the SDK in a demo environment, improving the overall developer experience. ## How Did You Test It? Via running and generating image locally ## Checklist - [x] I formatted the code using `cargo +nightly fmt --all` - [x] I addressed lints using `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where applicable
v1.113.0
c3ac0d0bd63a349cee7100e6e06c1f65e411ad58
c3ac0d0bd63a349cee7100e6e06c1f65e411ad58
juspay/hyperswitch
juspay__hyperswitch-7836
Bug: [FEATURE]: Add Refunds Retrieve and Rsync Flow in V2 apis. Add Refunds Retrieve and Rsync Flow in V2 apis.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 8b27fde3201..b6d6fb87e27 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3265,6 +3265,47 @@ ] } }, + "/v2/refunds/{id}": { + "get": { + "tags": [ + "Refunds" + ], + "summary": "Refunds - Retrieve", + "description": "Retrieves a Refund. This may be used to get the status of a previously initiated refund", + "operationId": "Retrieve a Refund", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The identifier for refund", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Refund retrieved", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RefundResponse" + } + } + } + }, + "404": { + "description": "Refund does not exist in our records" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/v2/process_tracker/revenue_recovery_workflow/{revenue_recovery_id}": { "get": { "tags": [ diff --git a/crates/api_models/src/events/refund.rs b/crates/api_models/src/events/refund.rs index 14e1984a760..08c6dd52c39 100644 --- a/crates/api_models/src/events/refund.rs +++ b/crates/api_models/src/events/refund.rs @@ -59,6 +59,13 @@ impl ApiEventMetric for RefundsRetrieveRequest { } } +#[cfg(feature = "v2")] +impl ApiEventMetric for refunds::RefundsRetrieveRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + None + } +} + #[cfg(feature = "v1")] impl ApiEventMetric for RefundUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index e8fcf39ca4e..775e0dfeef7 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -105,11 +105,19 @@ pub struct RefundsCreateRequest { pub metadata: Option<pii::SecretSerdeValue>, } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +#[derive(Default, Debug, Clone, Deserialize)] +pub struct RefundsRetrieveBody { + pub force_sync: Option<bool>, +} + +#[cfg(all(feature = "v2", feature = "refunds_v2"))] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrieveBody { pub force_sync: Option<bool>, } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RefundsRetrieveRequest { /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id. @@ -128,6 +136,22 @@ pub struct RefundsRetrieveRequest { pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] +pub struct RefundsRetrieveRequest { + /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id. + #[schema( + max_length = 30, + min_length = 30, + example = "ref_mbabizu24mvu3mela5njyhpit4" + )] + pub refund_id: common_utils::id_type::GlobalRefundId, + + /// `force_sync` with the connector to get refund details + /// (defaults to false) + pub force_sync: Option<bool>, +} + #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundUpdateRequest { diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index e197bc3c211..927965a5338 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -757,6 +757,24 @@ impl RefundUpdate { processor_refund_data: connector_refund_id.extract_hashed_data(), } } + + pub fn build_error_update_for_refund_failure( + refund_status: Option<storage_enums::RefundStatus>, + refund_error_message: Option<String>, + refund_error_code: Option<String>, + storage_scheme: &storage_enums::MerchantStorageScheme, + ) -> Self { + Self::ErrorUpdate { + refund_status, + refund_error_message, + refund_error_code, + updated_by: storage_scheme.to_string(), + connector_refund_id: None, + processor_refund_data: None, + unified_code: None, + unified_message: None, + } + } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index dea3d5f7128..3cb9cf766d6 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -763,6 +763,10 @@ impl PaymentIntent { }) .transpose() } + + pub fn get_currency(&self) -> storage_enums::Currency { + self.amount_details.currency + } } #[cfg(feature = "v1")] diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index b7f88345484..bb48871190e 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -148,6 +148,7 @@ Never share your secret api keys. Keep them guarded and secure. //Routes for refunds routes::refunds::refunds_create, + routes::refunds::refunds_retrieve, // Routes for Revenue Recovery flow under Process Tracker routes::revenue_recovery::revenue_recovery_pt_retrieve_api diff --git a/crates/openapi/src/routes/refunds.rs b/crates/openapi/src/routes/refunds.rs index 0ff0891ee54..5c55de2d177 100644 --- a/crates/openapi/src/routes/refunds.rs +++ b/crates/openapi/src/routes/refunds.rs @@ -64,6 +64,7 @@ pub async fn refunds_create() {} operation_id = "Retrieve a Refund", security(("api_key" = [])) )] +#[cfg(feature = "v1")] pub async fn refunds_retrieve() {} /// Refunds - Retrieve (POST) @@ -212,3 +213,23 @@ pub async fn refunds_filter_list() {} )] #[cfg(feature = "v2")] pub async fn refunds_create() {} + +/// Refunds - Retrieve +/// +/// Retrieves a Refund. This may be used to get the status of a previously initiated refund +#[utoipa::path( + get, + path = "/v2/refunds/{id}", + params( + ("id" = String, Path, description = "The identifier for refund") + ), + responses( + (status = 200, description = "Refund retrieved", body = RefundResponse), + (status = 404, description = "Refund does not exist in our records") + ), + tag = "Refunds", + operation_id = "Retrieve a Refund", + security(("api_key" = [])) +)] +#[cfg(feature = "v2")] +pub async fn refunds_retrieve() {} diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs index 89315006dc6..b6ccfe8376b 100644 --- a/crates/router/src/core/refunds_v2.rs +++ b/crates/router/src/core/refunds_v2.rs @@ -1,10 +1,17 @@ -use std::str::FromStr; +use std::{fmt::Debug, str::FromStr}; use api_models::{enums::Connector, refunds::RefundErrorDetails}; use common_utils::{id_type, types as common_utils_types}; use error_stack::{report, ResultExt}; -use hyperswitch_domain_models::router_data::{ErrorResponse, RouterData}; -use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}; +use hyperswitch_domain_models::{ + router_data::{ErrorResponse, RouterData}, + router_data_v2::RefundFlowData, +}; +use hyperswitch_interfaces::{ + api::{Connector as ConnectorTrait, ConnectorIntegration}, + connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2}, + integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}, +}; use router_env::{instrument, tracing}; use crate::{ @@ -202,20 +209,27 @@ pub async fn trigger_refund_to_gateway( Ok(response) } -async fn call_connector_service( +async fn call_connector_service<F>( state: &SessionState, connector: &api::ConnectorData, add_access_token_result: types::AddAccessTokenResult, - router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, + router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>, ) -> Result< - RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, + RouterData<F, types::RefundsData, types::RefundsResponseData>, error_stack::Report<errors::ConnectorError>, -> { +> +where + F: Debug + Clone + 'static, + dyn ConnectorTrait + Sync: + ConnectorIntegration<F, types::RefundsData, types::RefundsResponseData>, + dyn ConnectorV2 + Sync: + ConnectorIntegrationV2<F, RefundFlowData, types::RefundsData, types::RefundsResponseData>, +{ if !(add_access_token_result.connector_supports_access_token && router_data.access_token.is_none()) { let connector_integration: services::BoxedRefundConnectorIntegrationInterface< - api::Execute, + F, types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); @@ -382,9 +396,12 @@ pub fn get_refund_update_for_refund_response_data( } } -pub fn perform_integrity_check( - mut router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, -) -> RouterData<api::Execute, types::RefundsData, types::RefundsResponseData> { +pub fn perform_integrity_check<F>( + mut router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>, +) -> RouterData<F, types::RefundsData, types::RefundsResponseData> +where + F: Debug + Clone + 'static, +{ // Initiating Integrity check let integrity_result = check_refund_integrity(&router_data.request, &router_data.response); router_data.integrity_check = integrity_result; @@ -447,6 +464,276 @@ where request.check_integrity(request, connector_refund_id.to_owned()) } +// ********************************************** REFUND SYNC ********************************************** + +#[instrument(skip_all)] +pub async fn refund_retrieve_core_with_refund_id( + state: SessionState, + merchant_context: domain::MerchantContext, + profile: domain::Profile, + request: refunds::RefundsRetrieveRequest, +) -> errors::RouterResponse<refunds::RefundResponse> { + let refund_id = request.refund_id.clone(); + let db = &*state.store; + let profile_id = profile.get_id().to_owned(); + let refund = db + .find_refund_by_id( + &refund_id, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; + + let response = Box::pin(refund_retrieve_core( + state.clone(), + merchant_context, + Some(profile_id), + request, + refund, + )) + .await?; + + api::RefundResponse::foreign_try_from(response).map(services::ApplicationResponse::Json) +} + +#[instrument(skip_all)] +pub async fn refund_retrieve_core( + state: SessionState, + merchant_context: domain::MerchantContext, + profile_id: Option<id_type::ProfileId>, + request: refunds::RefundsRetrieveRequest, + refund: storage::Refund, +) -> errors::RouterResult<storage::Refund> { + let db = &*state.store; + + let key_manager_state = &(&state).into(); + core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?; + let payment_id = &refund.payment_id; + let payment_intent = db + .find_payment_intent_by_id( + key_manager_state, + payment_id, + merchant_context.get_merchant_key_store(), + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + let active_attempt_id = payment_intent + .active_attempt_id + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Active attempt id not found")?; + + let payment_attempt = db + .find_payment_attempt_by_id( + key_manager_state, + merchant_context.get_merchant_key_store(), + &active_attempt_id, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; + + let unified_translated_message = if let (Some(unified_code), Some(unified_message)) = + (refund.unified_code.clone(), refund.unified_message.clone()) + { + helpers::get_unified_translation( + &state, + unified_code, + unified_message.clone(), + state.locale.to_string(), + ) + .await + .or(Some(unified_message)) + } else { + refund.unified_message + }; + + let refund = storage::Refund { + unified_message: unified_translated_message, + ..refund + }; + + let response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) { + Box::pin(sync_refund_with_gateway( + &state, + &merchant_context, + &payment_attempt, + &payment_intent, + &refund, + )) + .await + } else { + Ok(refund) + }?; + Ok(response) +} + +fn should_call_refund(refund: &diesel_models::refund::Refund, force_sync: bool) -> bool { + // This implies, we cannot perform a refund sync & `the connector_refund_id` + // doesn't exist + let predicate1 = refund.connector_refund_id.is_some(); + + // This allows refund sync at connector level if force_sync is enabled, or + // checks if the refund has failed + let predicate2 = force_sync + || !matches!( + refund.refund_status, + diesel_models::enums::RefundStatus::Failure + | diesel_models::enums::RefundStatus::Success + ); + + predicate1 && predicate2 +} + +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +pub async fn sync_refund_with_gateway( + state: &SessionState, + merchant_context: &domain::MerchantContext, + payment_attempt: &storage::PaymentAttempt, + payment_intent: &storage::PaymentIntent, + refund: &storage::Refund, +) -> errors::RouterResult<storage::Refund> { + let db = &*state.store; + + let connector_id = refund.connector.to_string(); + let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &connector_id, + api::GetToken::Connector, + payment_attempt.merchant_connector_id.clone(), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get the connector")?; + + let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?; + + let mca = db + .find_merchant_connector_account_by_id( + &state.into(), + &mca_id, + merchant_context.get_merchant_key_store(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch merchant connector account")?; + + let connector_enum = mca.connector_name; + + let mut router_data = core_utils::construct_refund_router_data::<api::RSync>( + state, + connector_enum, + merchant_context, + payment_intent, + payment_attempt, + refund, + &mca, + ) + .await?; + + let add_access_token_result = + access_token::add_access_token(state, &connector, merchant_context, &router_data, None) + .await?; + + logger::debug!(refund_retrieve_router_data=?router_data); + + access_token::update_router_data_with_access_token_result( + &add_access_token_result, + &mut router_data, + &payments::CallConnectorAction::Trigger, + ); + + let connector_response = + call_connector_service(state, &connector, add_access_token_result, router_data) + .await + .to_refund_failed_response()?; + + let connector_response = perform_integrity_check(connector_response); + + let refund_update = + build_refund_update_for_rsync(&connector, merchant_context, connector_response); + + let response = state + .store + .update_refund( + refund.to_owned(), + refund_update, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::RefundNotFound) + .attach_printable_lazy(|| { + format!( + "Unable to update refund with refund_id: {}", + refund.id.get_string_repr() + ) + })?; + + // Implement outgoing webhook here + Ok(response) +} + +pub fn build_refund_update_for_rsync( + connector: &api::ConnectorData, + merchant_context: &domain::MerchantContext, + router_data_response: RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, +) -> storage::RefundUpdate { + let merchant_account = merchant_context.get_merchant_account(); + let storage_scheme = &merchant_context.get_merchant_account().storage_scheme; + + match router_data_response.response { + Err(error_message) => { + let refund_status = match error_message.status_code { + // marking failure for 2xx because this is genuine refund failure + 200..=299 => Some(enums::RefundStatus::Failure), + _ => None, + }; + let refund_error_message = error_message.reason.or(Some(error_message.message)); + let refund_error_code = Some(error_message.code); + + storage::RefundUpdate::build_error_update_for_refund_failure( + refund_status, + refund_error_message, + refund_error_code, + storage_scheme, + ) + } + Ok(response) => match router_data_response.integrity_check.clone() { + Err(err) => { + metrics::INTEGRITY_CHECK_FAILED.add( + 1, + router_env::metric_attributes!( + ("connector", connector.connector_name.to_string()), + ("merchant_id", merchant_account.get_id().clone()), + ), + ); + + let connector_refund_id = err + .connector_transaction_id + .map(common_utils_types::ConnectorTransactionId::from); + + storage::RefundUpdate::build_error_update_for_integrity_check_failure( + err.field_names, + connector_refund_id, + storage_scheme, + ) + } + Ok(()) => { + let connector_refund_id = + common_utils_types::ConnectorTransactionId::from(response.connector_refund_id); + + storage::RefundUpdate::build_refund_update( + connector_refund_id, + response.refund_status, + storage_scheme, + ) + } + }, + } +} + // ********************************************** VALIDATIONS ********************************************** #[instrument(skip_all)] diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index e123b792e75..d8b01bfd23e 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -252,7 +252,7 @@ pub async fn construct_refund_router_data<'a, F>( let status = payment_attempt.status; let payment_amount = payment_attempt.get_total_amount(); - let currency = payment_intent.amount_details.currency; + let currency = payment_intent.get_currency(); let payment_method_type = payment_attempt.payment_method_type; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9dc67be1d2d..68c88af3fd4 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1170,7 +1170,9 @@ impl Refunds { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/refunds").app_data(web::Data::new(state)); - route = route.service(web::resource("").route(web::post().to(refunds::refunds_create))); + route = route + .service(web::resource("").route(web::post().to(refunds::refunds_create))) + .service(web::resource("/{id}").route(web::get().to(refunds::refunds_retrieve))); route } diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index a7a4e5dddfb..65ea8720f99 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -168,6 +168,56 @@ pub async fn refunds_retrieve( .await } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[instrument(skip_all, fields(flow))] +pub async fn refunds_retrieve( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<common_utils::id_type::GlobalRefundId>, + query_params: web::Query<api_models::refunds::RefundsRetrieveBody>, +) -> HttpResponse { + let refund_request = refunds::RefundsRetrieveRequest { + refund_id: path.into_inner(), + force_sync: query_params.force_sync, + }; + let flow = match query_params.force_sync { + Some(true) => Flow::RefundsRetrieveForceSync, + _ => Flow::RefundsRetrieve, + }; + + tracing::Span::current().record("flow", flow.to_string()); + + Box::pin(api::server_wrap( + flow, + state, + &req, + refund_request, + |state, auth: auth::AuthenticationData, refund_request, _| { + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + refund_retrieve_core_with_refund_id( + state, + merchant_context, + auth.profile, + refund_request, + ) + }, + auth::auth_type( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::JWTAuth { + permission: Permission::ProfileRefundRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] /// Refunds - Retrieve (POST) /// diff --git a/crates/router/src/types/api/refunds.rs b/crates/router/src/types/api/refunds.rs index ff1f192fd45..8beaf7010f9 100644 --- a/crates/router/src/types/api/refunds.rs +++ b/crates/router/src/types/api/refunds.rs @@ -3,7 +3,8 @@ pub use api_models::refunds::RefundRequest; #[cfg(all(feature = "v2", feature = "refunds_v2"))] pub use api_models::refunds::RefundsCreateRequest; pub use api_models::refunds::{ - RefundResponse, RefundStatus, RefundType, RefundUpdateRequest, RefundsRetrieveRequest, + RefundResponse, RefundStatus, RefundType, RefundUpdateRequest, RefundsRetrieveBody, + RefundsRetrieveRequest, }; pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync}; pub use hyperswitch_interfaces::api::refunds::{Refund, RefundExecute, RefundSync};
2025-04-17T07:30:53Z
## 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 support for Refunds Retrieve flow and Refunds Sync flow (Rsync) in V2 apis. ### 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). --> Upon merging this PR, users can be able to fetch a particular refund. Whether to check its status or fetch it from the gateway using force_sync query parameter. ## 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 Payment Intent API call ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'api-key: dev_Oce2SOCaD6B7eTuE6o7fAoS0dJIOucG97Y1sS0O94JCzHg1Qh1emDSasTiFvVkIp' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_OIQz3QuZDrhyUteOS41r' \ --header 'Authorization: api-key=dev_Oce2SOCaD6B7eTuE6o7fAoS0dJIOucG97Y1sS0O94JCzHg1Qh1emDSasTiFvVkIp' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"automatic", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" } }' ``` - Response from the above call ``` { "id":"12345_pay_019642a2b1bb7653ae08d3a9c5559177", "status":"requires_payment_method", "amount_details":{ "order_amount":100, "currency":"USD", "shipping_cost":null, "order_tax_amount":null, "external_tax_calculation":"skip", "surcharge_calculation":"skip", "surcharge_amount":null, "tax_on_surcharge":null }, "client_secret":"cs_019642a2b25a7301962eaf25dbdb22fd", "profile_id":"pro_OIQz3QuZDrhyUteOS41r", "merchant_reference_id":null, "routing_algorithm_id":null, "capture_method":"automatic", "authentication_type":"no_three_ds", "billing":{ "address":{ "city":null, "country":null, "line1":null, "line2":null, "line3":null, "zip":null, "state":null, "first_name":"John", "last_name":"Dough" }, "phone":null, "email":"[email protected]" }, "shipping":{ "address":{ "city":"Karwar", "country":null, "line1":null, "line2":null, "line3":null, "zip":"581301", "state":"Karnataka", "first_name":"John", "last_name":"Dough" }, "phone":null, "email":"[email protected]" }, "customer_id":null, "customer_present":"present", "description":null, "return_url":null, "setup_future_usage":"on_session", "apply_mit_exemption":"Skip", "statement_descriptor":null, "order_details":null, "allowed_payment_method_types":null, "metadata":null, "connector_metadata":null, "feature_metadata":null, "payment_link_enabled":"Skip", "payment_link_config":null, "request_incremental_authorization":"default", "expires_on":"2025-04-17T07:39:40.883Z", "frm_metadata":null, "request_external_three_ds_authentication":"Skip" } ``` - Confirm Intent API Call ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_019642a2b1bb7653ae08d3a9c5559177/confirm-intent' \ --header 'x-client-secret: cs_019642a2b25a7301962eaf25dbdb22fd' \ --header 'x-profile-id: pro_OIQz3QuZDrhyUteOS41r' \ --header 'Content-Type: application/json' \ --header 'Authorization: publishable-key=pk_dev_ed28381f289249908a9fc946f11bf871,client-secret=cs_01963eaad7087700a02f86c215139747' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "1x.x.x.31" } }' ``` - Response from the above call ``` { "id":"12345_pay_019642a2b1bb7653ae08d3a9c5559177", "status":"succeeded", "amount":{ "order_amount":100, "currency":"USD", "shipping_cost":null, "order_tax_amount":null, "external_tax_calculation":"skip", "surcharge_calculation":"skip", "surcharge_amount":null, "tax_on_surcharge":null, "net_amount":100, "amount_to_capture":null, "amount_capturable":0, "amount_captured":100 }, "customer_id":null, "connector":"stripe", "created":"2025-04-17T07:24:40.884Z", "payment_method_data":{ "billing":null }, "payment_method_type":"card", "payment_method_subtype":"credit", "connector_transaction_id":"pi_3REmpOD5R7gDAGff0MLPnmeN", "connector_reference_id":null, "merchant_connector_id":"mca_sank3uwIE62b8Fzr90a6", "browser_info":null, "error":null, "shipping":null, "billing":null, "attempts":null, "connector_token_details":{ "token":"pm_1REmpOD5R7gDAGffAT3f1rIN", "connector_token_request_reference_id":"Ow8Jd6RrV0u6t2qyST" }, "payment_method_id":null, "next_action":null, "return_url":"https://google.com/success", "authentication_type":"no_three_ds", "authentication_type_applied":"no_three_ds" } ``` - Refunds Create API call ``` curl --location 'http://localhost:8080/v2/refunds' \ --header 'X-Profile-Id: pro_OIQz3QuZDrhyUteOS41r' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Oce2SOCaD6B7eTuE6o7fAoS0dJIOucG97Y1sS0O94JCzHg1Qh1emDSasTiFvVkIp' \ --data '{ "payment_id":"12345_pay_019642a2b1bb7653ae08d3a9c5559177", "merchant_reference_id":"1744874778", "reason":"Paid by mistake", "metadata":{ "foo":"bar" } }' ``` - Response from the above call ``` { "id": "12345_ref_019642a487767f20bb8fa4a34d70da4a", "payment_id": "12345_pay_019642a2b1bb7653ae08d3a9c5559177", "merchant_reference_id": "1744874801", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-04-17T07:26:41.030Z", "updated_at": "2025-04-17T07:26:42.057Z", "connector": "stripe", "profile_id": "pro_OIQz3QuZDrhyUteOS41r", "merchant_connector_id": "mca_sank3uwIE62b8Fzr90a6", "connector_refund_reference_id": null } ``` - Refunds Retrieve API call ``` curl --location 'http://localhost:8080/v2/refunds/12345_ref_019642a487767f20bb8fa4a34d70da4a' \ --header 'x-profile-id: pro_OIQz3QuZDrhyUteOS41r' \ --header 'api-key: dev_Oce2SOCaD6B7eTuE6o7fAoS0dJIOucG97Y1sS0O94JCzHg1Qh1emDSasTiFvVkIp' ``` - Response from the above call ``` { "id": "12345_ref_019642a487767f20bb8fa4a34d70da4a", "payment_id": "12345_pay_019642a2b1bb7653ae08d3a9c5559177", "merchant_reference_id": "1744874801", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-04-17T07:26:41.030Z", "updated_at": "2025-04-17T07:26:42.057Z", "connector": "stripe", "profile_id": "pro_OIQz3QuZDrhyUteOS41r", "merchant_connector_id": "mca_sank3uwIE62b8Fzr90a6", "connector_refund_reference_id": null } ``` - Refunds Retrieve api call with `force_sync=True` in query ``` curl --location 'http://localhost:8080/v2/refunds/12345_ref_019642a487767f20bb8fa4a34d70da4a?force_sync=true' \ --header 'x-profile-id: pro_OIQz3QuZDrhyUteOS41r' \ --header 'api-key: dev_Oce2SOCaD6B7eTuE6o7fAoS0dJIOucG97Y1sS0O94JCzHg1Qh1emDSasTiFvVkIp' \ --data '' ``` - Response from the above call ``` { "id": "12345_ref_019642a487767f20bb8fa4a34d70da4a", "payment_id": "12345_pay_019642a2b1bb7653ae08d3a9c5559177", "merchant_reference_id": "1744874801", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-04-17T07:26:41.030Z", "updated_at": "2025-04-17T08:38:46.639Z", "connector": "stripe", "profile_id": "pro_OIQz3QuZDrhyUteOS41r", "merchant_connector_id": "mca_sank3uwIE62b8Fzr90a6", "connector_refund_reference_id": null } ``` ## 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.114.0
31e109a9a1367ef53786c146604b31fca69b15ef
31e109a9a1367ef53786c146604b31fca69b15ef
juspay/hyperswitch
juspay__hyperswitch-7837
Bug: [FEATURE] connector's sandbox testing via magic values ### Feature Description Connectors provide sending magic values for certain fields in their API requests. These values can be used to simulate different error scenarios. For most of the cases across all the connectors, these can be set in the already present fields. For a few cases, extra fields are needed to be passed to the connector (eg: payment method holder name for MIT payments for Adyen). For such cases, the fields are not necessary in the real environment but necessary for simulating certain scenarios. This feature allows the end merchants to simulate different scenarios in the sandbox environment. ### Possible Implementation There are two parts to this for the implementation 1. Provision sending these fields by the merchant in the payments API request (structured metadata) 2. Consume these fields on a connector to connector basis as per the requirement Step 1 - Expose a field in `connector_metadata` for Adyen - With below fields for now - holder_name: Option<String> Sample body in the payments request ``` { ... "connector_metadata": { "adyen": { "testing": { "holder_name": "CARD_EXPIRED" } } } ... } ``` Step 2 - In non prod environment, pass this to connector integration for below actions - Authorize - SetupMandate - Refund Step 3 - Consume these fields in connector integration as per requirement Step 4 - Consume `holder_name` in MIT requests for Adyen integration ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 10682866ab7..e068f12f4be 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3775,6 +3775,17 @@ }, "additionalProperties": false }, + "AdyenConnectorMetadata": { + "type": "object", + "required": [ + "testing" + ], + "properties": { + "testing": { + "$ref": "#/components/schemas/AdyenTestingData" + } + } + }, "AdyenSplitData": { "type": "object", "description": "Fee information for Split Payments to be charged on the payment being collected for Adyen", @@ -3848,6 +3859,18 @@ "Vat" ] }, + "AdyenTestingData": { + "type": "object", + "required": [ + "holder_name" + ], + "properties": { + "holder_name": { + "type": "string", + "description": "Holder name to be sent to Adyen for a card payment(CIT) or a generic payment(MIT). This value overrides the values for card.card_holder_name and applies during both CIT and MIT payment transactions." + } + } + }, "AirwallexData": { "type": "object", "properties": { @@ -7960,6 +7983,14 @@ } ], "nullable": true + }, + "adyen": { + "allOf": [ + { + "$ref": "#/components/schemas/AdyenConnectorMetadata" + } + ], + "nullable": true } } }, diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index dafeaf65c03..0a372e34ce0 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -6069,6 +6069,17 @@ }, "additionalProperties": false }, + "AdyenConnectorMetadata": { + "type": "object", + "required": [ + "testing" + ], + "properties": { + "testing": { + "$ref": "#/components/schemas/AdyenTestingData" + } + } + }, "AdyenSplitData": { "type": "object", "description": "Fee information for Split Payments to be charged on the payment being collected for Adyen", @@ -6142,6 +6153,18 @@ "Vat" ] }, + "AdyenTestingData": { + "type": "object", + "required": [ + "holder_name" + ], + "properties": { + "holder_name": { + "type": "string", + "description": "Holder name to be sent to Adyen for a card payment(CIT) or a generic payment(MIT). This value overrides the values for card.card_holder_name and applies during both CIT and MIT payment transactions." + } + } + }, "AirwallexData": { "type": "object", "properties": { @@ -10010,6 +10033,14 @@ } ], "nullable": true + }, + "adyen": { + "allOf": [ + { + "$ref": "#/components/schemas/AdyenConnectorMetadata" + } + ], + "nullable": true } } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 011fd7e4431..52b3b893dde 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -6720,6 +6720,7 @@ pub struct ConnectorMetadata { pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, + pub adyen: Option<AdyenConnectorMetadata>, } impl ConnectorMetadata { @@ -6770,6 +6771,18 @@ pub struct BraintreeData { pub merchant_config_currency: Option<api_enums::Currency>, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct AdyenConnectorMetadata { + pub testing: AdyenTestingData, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct AdyenTestingData { + /// Holder name to be sent to Adyen for a card payment(CIT) or a generic payment(MIT). This value overrides the values for card.card_holder_name and applies during both CIT and MIT payment transactions. + #[schema(value_type = String)] + pub holder_name: Option<Secret<String>>, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index be6543d8b1c..c15affcc8aa 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -10,7 +10,7 @@ use common_enums::enums as storage_enums; use common_utils::ext_traits::OptionExt; use common_utils::{ errors::{CustomResult, ParsingError}, - ext_traits::Encode, + ext_traits::{Encode, ValueExt}, pii::Email, request::Method, types::MinorUnit, @@ -1222,6 +1222,7 @@ pub struct AdyenMandate { #[serde(rename = "type")] payment_type: PaymentType, stored_payment_method_id: Secret<String>, + holder_name: Option<Secret<String>>, } #[serde_with::skip_serializing_none] @@ -2008,13 +2009,21 @@ impl TryFrom<(&BankDebitData, &PaymentsAuthorizeRouterData)> for AdyenPaymentMet account_number, sort_code, .. - } => Ok(AdyenPaymentMethod::BacsDirectDebit(Box::new( - BacsDirectDebitData { - bank_account_number: account_number.clone(), - bank_location_id: sort_code.clone(), - holder_name: item.get_billing_full_name()?, - }, - ))), + } => { + let testing_data = item + .request + .get_connector_testing_data() + .map(AdyenTestingData::try_from) + .transpose()?; + let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name); + Ok(AdyenPaymentMethod::BacsDirectDebit(Box::new( + BacsDirectDebitData { + bank_account_number: account_number.clone(), + bank_location_id: sort_code.clone(), + holder_name: test_holder_name.unwrap_or(item.get_billing_full_name()?), + }, + ))) + } BankDebitData::BecsBankDebit { .. } => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyen"), @@ -2396,30 +2405,38 @@ impl TryFrom<(&BankRedirectData, &PaymentsAuthorizeRouterData)> for AdyenPayment card_exp_month, card_exp_year, .. - } => Ok(AdyenPaymentMethod::BancontactCard(Box::new(AdyenCard { - brand: Some(CardBrand::Bcmc), - number: card_number - .as_ref() - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "bancontact_card.card_number", - })? - .clone(), - expiry_month: card_exp_month - .as_ref() - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "bancontact_card.card_exp_month", - })? - .clone(), - expiry_year: card_exp_year - .as_ref() - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "bancontact_card.card_exp_year", - })? - .clone(), - holder_name: Some(item.get_billing_full_name()?), - cvc: None, - network_payment_reference: None, - }))), + } => { + let testing_data = item + .request + .get_connector_testing_data() + .map(AdyenTestingData::try_from) + .transpose()?; + let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name); + Ok(AdyenPaymentMethod::BancontactCard(Box::new(AdyenCard { + brand: Some(CardBrand::Bcmc), + number: card_number + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "bancontact_card.card_number", + })? + .clone(), + expiry_month: card_exp_month + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "bancontact_card.card_exp_month", + })? + .clone(), + expiry_year: card_exp_year + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "bancontact_card.card_exp_year", + })? + .clone(), + holder_name: test_holder_name.or(Some(item.get_billing_full_name()?)), + cvc: None, + network_payment_reference: None, + }))) + } BankRedirectData::Bizum { .. } => Ok(AdyenPaymentMethod::Bizum), BankRedirectData::Blik { blik_code } => { Ok(AdyenPaymentMethod::Blik(Box::new(BlikRedirectionData { @@ -2684,6 +2701,13 @@ impl let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_router_return_url()?; let payment_method_type = item.router_data.request.payment_method_type; + let testing_data = item + .router_data + .request + .get_connector_testing_data() + .map(AdyenTestingData::try_from) + .transpose()?; + let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name); let payment_method = match mandate_ref_id { payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids) => { let adyen_mandate = AdyenMandate { @@ -2696,6 +2720,7 @@ impl .get_connector_mandate_id() .ok_or_else(missing_field_err("mandate_id"))?, ), + holder_name: test_holder_name, }; Ok::<PaymentMethod<'_>, Self::Error>(PaymentMethod::AdyenMandatePaymentMethod( Box::new(adyen_mandate), @@ -2727,7 +2752,7 @@ impl .get_expiry_year_4_digit() .clone(), cvc: None, - holder_name: card_holder_name, + holder_name: test_holder_name.or(card_holder_name), brand: Some(brand), network_payment_reference: Some(Secret::new(network_mandate_id)), }; @@ -2768,7 +2793,7 @@ impl number: token_data.get_network_token(), expiry_month: token_data.get_network_token_expiry_month(), expiry_year: token_data.get_expiry_year_4_digit(), - holder_name: card_holder_name, + holder_name: test_holder_name.or(card_holder_name), brand: Some(brand), // FIXME: Remove hardcoding network_payment_reference: Some(Secret::new( network_mandate_id.network_transaction_id, @@ -2879,7 +2904,15 @@ impl TryFrom<(&AdyenRouterData<&PaymentsAuthorizeRouterData>, &Card)> for AdyenP let country_code = get_country_code(item.router_data.get_optional_billing()); let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_router_return_url()?; - let card_holder_name = item.router_data.get_optional_billing_full_name(); + let testing_data = item + .router_data + .request + .get_connector_testing_data() + .map(AdyenTestingData::try_from) + .transpose()?; + let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name); + let card_holder_name = + test_holder_name.or(item.router_data.get_optional_billing_full_name()); let payment_method = PaymentMethod::AdyenPaymentMethod(Box::new( AdyenPaymentMethod::try_from((card_data, card_holder_name))?, )); @@ -5505,6 +5538,24 @@ pub struct DefenseDocuments { defense_document_type_code: String, } +#[derive(Debug, Deserialize)] +pub struct AdyenTestingData { + holder_name: Option<Secret<String>>, +} + +impl TryFrom<common_utils::pii::SecretSerdeValue> for AdyenTestingData { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(testing_data: common_utils::pii::SecretSerdeValue) -> Result<Self, Self::Error> { + let testing_data = testing_data + .expose() + .parse_value::<Self>("AdyenTestingData") + .change_context(errors::ConnectorError::InvalidDataFormat { + field_name: "connector_metadata.adyen.testing", + })?; + Ok(testing_data) + } +} + impl TryFrom<&SubmitEvidenceRouterData> for Evidence { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &SubmitEvidenceRouterData) -> Result<Self, Self::Error> { @@ -5782,7 +5833,15 @@ impl let country_code = get_country_code(item.router_data.get_optional_billing()); let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_router_return_url()?; - let card_holder_name = item.router_data.get_optional_billing_full_name(); + let testing_data = item + .router_data + .request + .get_connector_testing_data() + .map(AdyenTestingData::try_from) + .transpose()?; + let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name); + let card_holder_name = + test_holder_name.or(item.router_data.get_optional_billing_full_name()); let payment_method = PaymentMethod::AdyenPaymentMethod(Box::new( AdyenPaymentMethod::try_from((token_data, card_holder_name))?, )); diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 60cb878d9a3..c693d4789ca 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -1685,6 +1685,7 @@ pub trait PaymentsAuthorizeRequestData { fn get_card_network_from_additional_payment_method_data( &self, ) -> Result<enums::CardNetwork, Error>; + fn get_connector_testing_data(&self) -> Option<pii::SecretSerdeValue>; } impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData { @@ -1905,6 +1906,9 @@ impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData { .into()), } } + fn get_connector_testing_data(&self) -> Option<pii::SecretSerdeValue> { + self.connector_testing_data.clone() + } } pub trait PaymentsCaptureRequestData { @@ -5998,6 +6002,7 @@ pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data( shipping_cost: data.request.shipping_cost, merchant_account_id: None, merchant_config_currency: None, + connector_testing_data: data.request.connector_testing_data.clone(), } } diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 7a91f82f306..1dc88ed95ae 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -76,6 +76,7 @@ pub struct PaymentsAuthorizeData { pub additional_payment_method_data: Option<AdditionalPaymentData>, pub merchant_account_id: Option<Secret<String>>, pub merchant_config_currency: Option<storage_enums::Currency>, + pub connector_testing_data: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct PaymentsPostSessionTokensData { @@ -935,4 +936,5 @@ pub struct SetupMandateRequestData { // MinorUnit for amount framework pub minor_amount: Option<MinorUnit>, pub shipping_cost: Option<MinorUnit>, + pub connector_testing_data: Option<pii::SecretSerdeValue>, } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 5d9ccfab2a4..6dc61d4bf4a 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -734,6 +734,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsUpdateMetadataRequest, api_models::payments::PaymentsUpdateMetadataResponse, api_models::payments::CtpServiceDetails, + api_models::payments::AdyenConnectorMetadata, + api_models::payments::AdyenTestingData, api_models::feature_matrix::FeatureMatrixListResponse, api_models::feature_matrix::FeatureMatrixRequest, api_models::feature_matrix::ConnectorFeatureMatrixResponse, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 2629b1b8b7d..b7f88345484 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -701,6 +701,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::DisplayAmountOnSdk, api_models::payments::ErrorDetails, api_models::payments::CtpServiceDetails, + api_models::payments::AdyenConnectorMetadata, + api_models::payments::AdyenTestingData, api_models::feature_matrix::FeatureMatrixListResponse, api_models::feature_matrix::FeatureMatrixRequest, api_models::feature_matrix::ConnectorFeatureMatrixResponse, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 0628a7281f7..6ae4cf4ec72 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -307,6 +307,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( additional_payment_method_data: None, merchant_account_id: None, merchant_config_currency: None, + connector_testing_data: None, }; let connector_mandate_request_reference_id = payment_data .payment_attempt @@ -960,6 +961,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( shipping_cost: payment_data.payment_intent.amount_details.shipping_cost, capture_method: Some(payment_data.payment_intent.capture_method), complete_authorize_url, + connector_testing_data: None, }; let connector_mandate_request_reference_id = payment_data .payment_attempt @@ -3183,7 +3185,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz field_name: "browser_info", })?; - let order_category = additional_data + let connector_metadata = additional_data .payment_data .payment_intent .connector_metadata @@ -3193,21 +3195,16 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed parsing ConnectorMetadata") }) - .transpose()? - .and_then(|cm| cm.noon.and_then(|noon| noon.order_category)); + .transpose()?; - let braintree_metadata = additional_data - .payment_data - .payment_intent - .connector_metadata - .clone() - .map(|cm| { - cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed parsing ConnectorMetadata") - }) - .transpose()? - .and_then(|cm| cm.braintree); + let order_category = connector_metadata.as_ref().and_then(|cm| { + cm.noon + .as_ref() + .and_then(|noon| noon.order_category.clone()) + }); + let braintree_metadata = connector_metadata + .as_ref() + .and_then(|cm| cm.braintree.clone()); let merchant_account_id = braintree_metadata .as_ref() @@ -3301,6 +3298,30 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz .clone(); let shipping_cost = payment_data.payment_intent.shipping_cost; + let connector = api_models::enums::Connector::from_str(connector_name) + .change_context(errors::ConnectorError::InvalidConnectorName) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| { + format!("unable to parse connector name {connector_name:?}") + })?; + + let connector_testing_data = connector_metadata + .and_then(|cm| match connector { + api_models::enums::Connector::Adyen => cm + .adyen + .map(|adyen_cm| adyen_cm.testing) + .map(|testing_data| { + serde_json::to_value(testing_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse Adyen testing data") + }), + _ => None, + }) + .transpose()? + .map(pii::SecretSerdeValue::new); + Ok(Self { payment_method_data: (payment_method_data.get_required_value("payment_method_data")?), setup_future_usage: payment_data.payment_attempt.setup_future_usage_applied, @@ -3355,6 +3376,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz shipping_cost, merchant_account_id, merchant_config_currency, + connector_testing_data, }) } } @@ -4106,6 +4128,40 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ payment_data.creds_identifier.as_deref(), )); + let connector = api_models::enums::Connector::from_str(connector_name) + .change_context(errors::ConnectorError::InvalidConnectorName) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| { + format!("unable to parse connector name {connector_name:?}") + })?; + + let connector_testing_data = payment_data + .payment_intent + .connector_metadata + .as_ref() + .map(|cm| { + cm.clone() + .parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed parsing ConnectorMetadata") + }) + .transpose()? + .and_then(|cm| match connector { + api_models::enums::Connector::Adyen => cm + .adyen + .map(|adyen_cm| adyen_cm.testing) + .map(|testing_data| { + serde_json::to_value(testing_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse Adyen testing data") + }), + _ => None, + }) + .transpose()? + .map(pii::SecretSerdeValue::new); + Ok(Self { currency: payment_data.currency, confirm: true, @@ -4138,6 +4194,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ webhook_url, complete_authorize_url, capture_method: payment_data.payment_attempt.capture_method, + connector_testing_data, }) } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 2927bc4c8fa..057543d9632 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -923,6 +923,7 @@ impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData { shipping_cost: data.request.shipping_cost, merchant_account_id: None, merchant_config_currency: None, + connector_testing_data: data.request.connector_testing_data.clone(), } } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index a2a4cf88f65..223c3e5638d 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -63,6 +63,7 @@ impl VerifyConnectorData { shipping_cost: None, merchant_account_id: None, merchant_config_currency: None, + connector_testing_data: None, } } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 6a7239b5b46..2bc4c9f24eb 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -987,6 +987,7 @@ impl Default for PaymentAuthorizeType { shipping_cost: None, merchant_account_id: None, merchant_config_currency: None, + connector_testing_data: None, }; Self(data) }
2025-04-23T05:27:26Z
## 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 connector testing data in payment requests, specifically for Adyen connector. It allows merchants to send testing values via `connector_metadata` to simulate different scenarios in the sandbox environment. The implementation includes: 1. Added a new structure `AdyenConnectorMetadata` and `AdyenTestingData` in the API models 2. Modified the Adyen connector payment flows (both CIT and MIT) across different payment methods to accept and process the testing data The holder_name in testing data will override card_holder_name in the connector's payment request, allowing merchants to test specific scenarios without affecting their production implementation. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context Connectors like Adyen provide special values for certain fields that can be used to simulate different error scenarios in their sandbox environments. These special values help merchants test error handling without requiring them to modify their actual implementation. For example, sending a specific holder name value like "CARD_EXPIRED" can simulate a card expiration error from Adyen. This feature enables merchants to test various error scenarios in a systematic way through HyperSwitch API without changing their integration code. ## How did you test it? <details> <summary>1. Simulate Adyen's CARD_EXPIRED error through testing data in connector_metadata for CIT</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UEgACZ01bXHeFIrvN93I7h3sWWs4V0LTiJwPQRdI9OQzV4lZcVzLQ1mnfAprp5nx' \ --data-raw '{"amount":10,"currency":"EUR","confirm":true,"profile_id":"pro_HPqNgWlKGAgwQms0jwIF","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","setup_future_usage":"off_session","connector":["adyen"],"customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4111111111111111","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"Test User","card_cvc":"737"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"IT","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{"holder_name":"CARD_EXPIRED x This is my error message"}}},"session_expiry":60}' Expectations 1. Payment fails with the specified string in testing data's holder name 2. Testing data's holder name takes precedence over the value passed in payment_method_data card_holder_name Response {"payment_id":"pay_YAtEbtMJOeLlpgy6Qo1q","merchant_id":"merchant_1745378456","status":"failed","amount":10,"net_amount":10,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"adyen","client_secret":"pay_YAtEbtMJOeLlpgy6Qo1q_secret_wDnisrGKMPVJ1yITYAgB","created":"2025-04-23T04:31:43.728Z","currency":"EUR","customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","customer":{"id":"cus_xPhu4Ugm5fIPkjIUQNaH","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"1111","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"Test User","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":"6","error_message":"Expired Card","unified_code":"UE_9000","unified_message":"Something went wrong","payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","created_at":1745382703,"expires":1745386303,"secret":"epk_deacab31d1e6413291eada3764b2986c"},"manual_retry_allowed":true,"connector_transaction_id":"LW79V9ZRB72FMNT5","frm_message":null,"metadata":null,"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null,"adyen":{"testing":{"holder_name":"CARD_EXPIRED x This is my error message"}}},"feature_metadata":null,"reference_id":null,"payment_link":null,"profile_id":"pro_HPqNgWlKGAgwQms0jwIF","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_OSy4xc1t36A2rIA8IJcn","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-23T04:32:43.728Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-23T04:31:45.103Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":"This is my error message"} </details> <details> <summary>2. Simulate Adyen's CARD_EXPIRED error through testing data in connector_metadata for MIT<summary> cURL (for creating mandates) curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UEgACZ01bXHeFIrvN93I7h3sWWs4V0LTiJwPQRdI9OQzV4lZcVzLQ1mnfAprp5nx' \ --data-raw '{"amount":10,"currency":"EUR","confirm":true,"profile_id":"pro_HPqNgWlKGAgwQms0jwIF","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","setup_future_usage":"off_session","connector":["adyen"],"customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4111111111111111","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"Test User","card_cvc":"737"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"IT","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"session_expiry":60}' Expectations 1. Payment succeeds 2. payment_method_id is retrieved Response {"payment_id":"pay_Bc8m48deiQPthw9eNKB2","merchant_id":"merchant_1745378456","status":"succeeded","amount":10,"net_amount":10,"shipping_cost":null,"amount_capturable":0,"amount_received":10,"connector":"adyen","client_secret":"pay_Bc8m48deiQPthw9eNKB2_secret_x78ITiMF1X73mI6bc4st","created":"2025-04-23T04:35:53.717Z","currency":"EUR","customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","customer":{"id":"cus_xPhu4Ugm5fIPkjIUQNaH","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"1111","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"Test User","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","created_at":1745382953,"expires":1745386553,"secret":"epk_ee929d43a2f3400d84b614ba30219d53"},"manual_retry_allowed":false,"connector_transaction_id":"D2XCLCJRGB9VWM75","frm_message":null,"metadata":null,"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null,"adyen":{"testing":{"holder_name":null}}},"feature_metadata":null,"reference_id":"pay_Bc8m48deiQPthw9eNKB2_1","payment_link":null,"profile_id":"pro_HPqNgWlKGAgwQms0jwIF","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_OSy4xc1t36A2rIA8IJcn","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-23T04:36:53.717Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_EJSd2QoapABA7TLpNrjp","payment_method_status":"active","updated":"2025-04-23T04:35:55.388Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"LQR35D9R636NHJ65","card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} cURL (Simulating error in MIT) curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_UEgACZ01bXHeFIrvN93I7h3sWWs4V0LTiJwPQRdI9OQzV4lZcVzLQ1mnfAprp5nx' \ --data-raw '{"amount":6500,"currency":"EUR","confirm":true,"capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","email":"[email protected]","name":"John Doe","phone":"999999999","profile_id":"pro_HPqNgWlKGAgwQms0jwIF","phone_country_code":"+65","description":"Its my first payment request","return_url":"https://hyperswitch.io","off_session":true,"recurring_details":{"type":"payment_method_id","data":"pm_EJSd2QoapABA7TLpNrjp"},"connector":["adyen"],"statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true},"connector_metadata":{"adyen":{"testing":{"holder_name":"CARD_EXPIRED x MIT error message"}}}}' Expectations 1. MIT payment fails with the specified error in testing data's holder name field Response {"payment_id":"pay_fRuTbjd8yFPgBk9NHn1U","merchant_id":"merchant_1745378456","status":"failed","amount":6500,"net_amount":6500,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"adyen","client_secret":"pay_fRuTbjd8yFPgBk9NHn1U_secret_AZm2NYex5skj3qtRYmiy","created":"2025-04-23T04:37:46.301Z","currency":"EUR","customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","customer":{"id":"cus_xPhu4Ugm5fIPkjIUQNaH","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+65"},"description":"Its my first payment request","refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":true,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"1111","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"Test User","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://hyperswitch.io/","authentication_type":"no_three_ds","statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","next_action":null,"cancellation_reason":null,"error_code":"6","error_message":"Expired Card","unified_code":"UE_9000","unified_message":"Something went wrong","payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_xPhu4Ugm5fIPkjIUQNaH","created_at":1745383066,"expires":1745386666,"secret":"epk_99ac0c08e6d843ae9d15e6f280822f2f"},"manual_retry_allowed":true,"connector_transaction_id":"JKS4HVG55L4VWM75","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null,"adyen":{"testing":{"holder_name":"CARD_EXPIRED x MIT error message"}}},"feature_metadata":null,"reference_id":null,"payment_link":null,"profile_id":"pro_HPqNgWlKGAgwQms0jwIF","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_OSy4xc1t36A2rIA8IJcn","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-23T04:52:46.301Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_EJSd2QoapABA7TLpNrjp","payment_method_status":"active","updated":"2025-04-23T04:37:47.572Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"LQR35D9R636NHJ65","card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":"MIT error message"} </details> <details> <summary>Automated cypress tests for Adyen (Ideal bank redirection fails as expected)</summary> ![Screenshot 2025-04-24 at 8 28 21 PM](https://github.com/user-attachments/assets/d9119546-f8b5-4852-a141-7456e490935d) </details> ## 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.113.0
2c9b8abdb58d5b97f9d01a112569ad82b99ea00d
2c9b8abdb58d5b97f9d01a112569ad82b99ea00d
juspay/hyperswitch
juspay__hyperswitch-7833
Bug: [BUG (CYPRESS)] Hard coded card expiry resulting in few tests to fail updating card expiry resulted in unintended after effects for specific connectors like adyen where it expects the user to pass a specific card expiry year (`30` instead of `55` or any other number). we cannot hard code connector names in spec files to exclude them from getting updated. neither we can go ahead and pull in another set of connector configs for this. so, i feel, it is better to just restrict that field from getting updated.
2025-04-17T06:20:59Z
## 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 --> the reason behind this pr is that there are a few connectors like adyen that expects the user to pass specific card expiry year and having it hard coded like we had until now results in unintended issues resulting the tests to fail. ### 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). --> updating card expiry resulted in unintended after effects for specific connectors like adyen where it expects the user to pass a specific card expiry year. we cannot hard code connector names in spec files. neither we can go ahead and pull in another set of connector configs for this. so, it is more viable to remove the entire field from getting update since updating one field should be more than enough. closes https://github.com/juspay/hyperswitch/issues/7833 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ran test against adyen since it was the one threw this error. not sure about other connectors but yeah, this change should fix them as well: <img width="524" alt="image" src="https://github.com/user-attachments/assets/3a9cf73f-0e60-4e0a-9e29-a2af8a63db3f" /> <img width="952" alt="image" src="https://github.com/user-attachments/assets/283eaf66-9233-4a20-83e1-e4eb808110fb" /> (failure is from ideal bank redirect redirection) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `npm run format` - [x] I addressed lints thrown by `npm run lint -- --fix` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
82bc46166b6157c43116e97a4b9bda8ecfd6285c
82bc46166b6157c43116e97a4b9bda8ecfd6285c
juspay/hyperswitch
juspay__hyperswitch-7817
Bug: Hubspot api integration Closes issue https://github.com/juspay/hyperswitch-control-center-cloud/issues/28
diff --git a/Cargo.lock b/Cargo.lock index f0b8ce94980..d2ae0213703 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2936,6 +2936,7 @@ dependencies = [ "dyn-clone", "error-stack", "hex", + "http 0.2.12", "http-body-util", "hyper 0.14.30", "hyper-proxy", @@ -2945,6 +2946,8 @@ dependencies = [ "masking", "once_cell", "prost", + "quick-xml", + "reqwest 0.11.27", "router_env", "serde", "thiserror 1.0.63", @@ -2953,6 +2956,7 @@ dependencies = [ "tonic-build", "tonic-reflection", "tonic-types", + "url", "vaultrs", ] @@ -6531,7 +6535,6 @@ dependencies = [ "openssl", "payment_methods", "pm_auth", - "quick-xml", "rand", "rand_chacha", "rdkafka", diff --git a/config/config.example.toml b/config/config.example.toml index e505e9106f0..bd1a1639608 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -970,6 +970,13 @@ encryption_manager = "aws_kms" # Encryption manager client to be used key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. +[crm] +crm_manager = "hubspot_proxy" # Crm manager client to be used + +[crm.hubspot_proxy] +form_id="hubspot_proxy_form_id" # Form ID for Hubspot integration +request_url="hubspot_proxy_request_url" # Request URL for Hubspot API + [opensearch] host = "https://localhost:9200" enabled = false diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 5621a4940e8..7c1866b7794 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -303,6 +303,14 @@ encryption_manager = "aws_kms" # Encryption manager client to be used key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data. region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. +[crm] +crm_manager = "hubspot_proxy" # Crm manager client to be used + +[crm.hubspot_proxy] +form_id="" # Form ID for Hubspot integration +request_url="" # Request URL for Hubspot API + + [multitenancy] enabled = false global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs index 8e734d31b53..fe590f6c7d5 100644 --- a/crates/api_models/src/user/dashboard_metadata.rs +++ b/crates/api_models/src/user/dashboard_metadata.rs @@ -99,12 +99,13 @@ pub struct ProdIntent { pub business_type: Option<String>, pub business_identifier: Option<String>, pub business_website: Option<String>, - pub poc_name: Option<String>, - pub poc_contact: Option<String>, + pub poc_name: Option<Secret<String>>, + pub poc_contact: Option<Secret<String>>, pub comments: Option<String>, pub is_completed: bool, #[serde(default)] pub product_type: MerchantProductType, + pub business_country_name: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index d722518154b..1606d731a21 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -176,3 +176,9 @@ pub const DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS: i32 = 3600; /// SOAP 1.1 Envelope Namespace pub const SOAP_ENV_NAMESPACE: &str = "http://schemas.xmlsoap.org/soap/envelope/"; + +/// The tag name used for identifying the host in metrics. +pub const METRICS_HOST_TAG_NAME: &str = "host"; + +/// API client request timeout (in seconds) +pub const REQUEST_TIME_OUT: u64 = 30; diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index ebab30eec70..9fdbbf133ca 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -41,6 +41,10 @@ tonic-reflection = { version = "0.12.2", optional = true } tonic-types = { version = "0.12.2", optional = true } hyper-util = { version = "0.1.9", optional = true } http-body-util = { version = "0.1.2", optional = true } +reqwest = { version = "0.11.27", features = ["rustls-tls"] } +http = "0.2.12" +url = { version = "2.5.0", features = ["serde"] } +quick-xml = { version = "0.31.0", features = ["serialize"] } # First party crates diff --git a/crates/external_services/src/crm.rs b/crates/external_services/src/crm.rs new file mode 100644 index 00000000000..ef2982fb380 --- /dev/null +++ b/crates/external_services/src/crm.rs @@ -0,0 +1,148 @@ +use std::sync::Arc; + +use common_utils::{ + errors::CustomResult, + ext_traits::ConfigExt, + request::{Method, Request, RequestBuilder, RequestContent}, +}; +use error_stack::ResultExt; +use http::header; +use hyperswitch_interfaces::{ + crm::{CrmInterface, CrmPayload}, + errors::HttpClientError, + types::Proxy, +}; +use reqwest; +use router_env::logger; + +use crate::{http_client, hubspot_proxy::HubspotRequest}; + +/// Hubspot Crm configuration +#[derive(Debug, Clone, serde::Deserialize)] +pub struct HubspotProxyConfig { + /// The ID of the Hubspot form to be submitted. + pub form_id: String, + + /// The URL to which the Hubspot form data will be sent. + pub request_url: String, +} + +impl HubspotProxyConfig { + /// Validates Hubspot configuration + pub(super) fn validate(&self) -> Result<(), InvalidCrmConfig> { + use common_utils::fp_utils::when; + + when(self.request_url.is_default_or_empty(), || { + Err(InvalidCrmConfig("request url must not be empty")) + })?; + + when(self.form_id.is_default_or_empty(), || { + Err(InvalidCrmConfig("form_id must not be empty")) + }) + } +} + +/// Error thrown when the crm config is invalid +#[derive(Debug, Clone)] +pub struct InvalidCrmConfig(pub &'static str); + +impl std::error::Error for InvalidCrmConfig {} + +impl std::fmt::Display for InvalidCrmConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "crm: {}", self.0) + } +} + +#[derive(Debug, Clone, Copy)] +/// NoCrm struct +pub struct NoCrm; + +/// Enum representing different Crm configurations +#[derive(Debug, Clone, Default, serde::Deserialize)] +#[serde(tag = "crm_manager")] +#[serde(rename_all = "snake_case")] +pub enum CrmManagerConfig { + /// Hubspot Crm configuration + HubspotProxy { + /// Hubspot Crm configuration + hubspot_proxy: HubspotProxyConfig, + }, + + /// No Crm configuration + #[default] + NoCrm, +} + +impl CrmManagerConfig { + /// Verifies that the client configuration is usable + pub fn validate(&self) -> Result<(), InvalidCrmConfig> { + match self { + Self::HubspotProxy { hubspot_proxy } => hubspot_proxy.validate(), + Self::NoCrm => Ok(()), + } + } + + /// Retrieves the appropriate Crm client based on the configuration. + pub async fn get_crm_client(&self) -> Arc<dyn CrmInterface> { + match self { + Self::HubspotProxy { hubspot_proxy } => Arc::new(hubspot_proxy.clone()), + Self::NoCrm => Arc::new(NoCrm), + } + } +} + +#[async_trait::async_trait] +impl CrmInterface for NoCrm { + async fn make_body(&self, _details: CrmPayload) -> RequestContent { + RequestContent::Json(Box::new(())) + } + + async fn make_request(&self, _body: RequestContent, _origin_base_url: String) -> Request { + RequestBuilder::default().build() + } + + async fn send_request( + &self, + _proxy: &Proxy, + _request: Request, + ) -> CustomResult<reqwest::Response, HttpClientError> { + logger::info!("No CRM configured!"); + Err(HttpClientError::UnexpectedState).attach_printable("No CRM configured!") + } +} + +#[async_trait::async_trait] +impl CrmInterface for HubspotProxyConfig { + async fn make_body(&self, details: CrmPayload) -> RequestContent { + RequestContent::FormUrlEncoded(Box::new(HubspotRequest::new( + details.business_country_name.unwrap_or_default(), + self.form_id.clone(), + details.poc_name.unwrap_or_default(), + details.poc_email.clone().unwrap_or_default(), + details.legal_business_name.unwrap_or_default(), + details.business_website.unwrap_or_default(), + ))) + } + + async fn make_request(&self, body: RequestContent, origin_base_url: String) -> Request { + RequestBuilder::new() + .method(Method::Post) + .url(self.request_url.as_str()) + .set_body(body) + .attach_default_headers() + .headers(vec![( + header::ORIGIN.to_string(), + format!("{origin_base_url}/dashboard").into(), + )]) + .build() + } + + async fn send_request( + &self, + proxy: &Proxy, + request: Request, + ) -> CustomResult<reqwest::Response, HttpClientError> { + http_client::send_request(proxy, request, None).await + } +} diff --git a/crates/external_services/src/http_client.rs b/crates/external_services/src/http_client.rs new file mode 100644 index 00000000000..dedeb0c1983 --- /dev/null +++ b/crates/external_services/src/http_client.rs @@ -0,0 +1,182 @@ +use common_utils::{consts, errors::CustomResult, request::Request}; +use hyperswitch_interfaces::{errors::HttpClientError, types::Proxy}; +use request::{HeaderExt, RequestBuilderExt}; +use router_env::{instrument, logger, tracing}; +/// client module +pub mod client; +/// metrics module +pub mod metrics; +/// request module +pub mod request; +use std::{error::Error, time::Duration}; + +use common_utils::request::RequestContent; +pub use common_utils::request::{ContentType, Method, RequestBuilder}; +use error_stack::ResultExt; + +#[allow(missing_docs)] +#[instrument(skip_all)] +pub async fn send_request( + client_proxy: &Proxy, + request: Request, + option_timeout_secs: Option<u64>, +) -> CustomResult<reqwest::Response, HttpClientError> { + logger::info!(method=?request.method, headers=?request.headers, payload=?request.body, ?request); + + let url = url::Url::parse(&request.url).change_context(HttpClientError::UrlParsingFailed)?; + + let client = client::create_client(client_proxy, request.certificate, request.certificate_key)?; + + let headers = request.headers.construct_header_map()?; + let metrics_tag = router_env::metric_attributes!(( + consts::METRICS_HOST_TAG_NAME, + url.host_str().unwrap_or_default().to_owned() + )); + let request = { + match request.method { + Method::Get => client.get(url), + Method::Post => { + let client = client.post(url); + match request.body { + Some(RequestContent::Json(payload)) => client.json(&payload), + Some(RequestContent::FormData(form)) => client.multipart(form), + Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload), + Some(RequestContent::Xml(payload)) => { + let body = quick_xml::se::to_string(&payload) + .change_context(HttpClientError::BodySerializationFailed)?; + client.body(body).header("Content-Type", "application/xml") + } + Some(RequestContent::RawBytes(payload)) => client.body(payload), + None => client, + } + } + Method::Put => { + let client = client.put(url); + match request.body { + Some(RequestContent::Json(payload)) => client.json(&payload), + Some(RequestContent::FormData(form)) => client.multipart(form), + Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload), + Some(RequestContent::Xml(payload)) => { + let body = quick_xml::se::to_string(&payload) + .change_context(HttpClientError::BodySerializationFailed)?; + client.body(body).header("Content-Type", "application/xml") + } + Some(RequestContent::RawBytes(payload)) => client.body(payload), + None => client, + } + } + Method::Patch => { + let client = client.patch(url); + match request.body { + Some(RequestContent::Json(payload)) => client.json(&payload), + Some(RequestContent::FormData(form)) => client.multipart(form), + Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload), + Some(RequestContent::Xml(payload)) => { + let body = quick_xml::se::to_string(&payload) + .change_context(HttpClientError::BodySerializationFailed)?; + client.body(body).header("Content-Type", "application/xml") + } + Some(RequestContent::RawBytes(payload)) => client.body(payload), + None => client, + } + } + Method::Delete => client.delete(url), + } + .add_headers(headers) + .timeout(Duration::from_secs( + option_timeout_secs.unwrap_or(consts::REQUEST_TIME_OUT), + )) + }; + + // We cannot clone the request type, because it has Form trait which is not cloneable. So we are cloning the request builder here. + let cloned_send_request = request.try_clone().map(|cloned_request| async { + cloned_request + .send() + .await + .map_err(|error| match error { + error if error.is_timeout() => { + metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag); + HttpClientError::RequestTimeoutReceived + } + error if is_connection_closed_before_message_could_complete(&error) => { + metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag); + HttpClientError::ConnectionClosedIncompleteMessage + } + _ => HttpClientError::RequestNotSent(error.to_string()), + }) + .attach_printable("Unable to send request to connector") + }); + + let send_request = async { + request + .send() + .await + .map_err(|error| match error { + error if error.is_timeout() => { + metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag); + HttpClientError::RequestTimeoutReceived + } + error if is_connection_closed_before_message_could_complete(&error) => { + metrics::REQUEST_BUILD_FAILURE.add(1, metrics_tag); + HttpClientError::ConnectionClosedIncompleteMessage + } + _ => HttpClientError::RequestNotSent(error.to_string()), + }) + .attach_printable("Unable to send request to connector") + }; + + let response = common_utils::metrics::utils::record_operation_time( + send_request, + &metrics::EXTERNAL_REQUEST_TIME, + metrics_tag, + ) + .await; + // Retry once if the response is connection closed. + // + // This is just due to the racy nature of networking. + // hyper has a connection pool of idle connections, and it selected one to send your request. + // Most of the time, hyper will receive the server’s FIN and drop the dead connection from its pool. + // But occasionally, a connection will be selected from the pool + // and written to at the same time the server is deciding to close the connection. + // Since hyper already wrote some of the request, + // it can’t really retry it automatically on a new connection, since the server may have acted already + match response { + Ok(response) => Ok(response), + Err(error) + if error.current_context() == &HttpClientError::ConnectionClosedIncompleteMessage => + { + metrics::AUTO_RETRY_CONNECTION_CLOSED.add(1, metrics_tag); + match cloned_send_request { + Some(cloned_request) => { + logger::info!( + "Retrying request due to connection closed before message could complete" + ); + common_utils::metrics::utils::record_operation_time( + cloned_request, + &metrics::EXTERNAL_REQUEST_TIME, + metrics_tag, + ) + .await + } + None => { + logger::info!("Retrying request due to connection closed before message could complete failed as request is not cloneable"); + Err(error) + } + } + } + err @ Err(_) => err, + } +} + +fn is_connection_closed_before_message_could_complete(error: &reqwest::Error) -> bool { + let mut source = error.source(); + while let Some(err) = source { + if let Some(hyper_err) = err.downcast_ref::<hyper::Error>() { + if hyper_err.is_incomplete_message() { + return true; + } + } + source = err.source(); + } + false +} diff --git a/crates/external_services/src/http_client/client.rs b/crates/external_services/src/http_client/client.rs new file mode 100644 index 00000000000..0696c9e76b9 --- /dev/null +++ b/crates/external_services/src/http_client/client.rs @@ -0,0 +1,131 @@ +use std::time::Duration; + +use base64::Engine; +use common_utils::consts::BASE64_ENGINE; +pub use common_utils::errors::CustomResult; +use error_stack::ResultExt; +use hyperswitch_interfaces::{errors::HttpClientError, types::Proxy}; +use masking::ExposeInterface; +use once_cell::sync::OnceCell; + +static DEFAULT_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); + +// We may need to use outbound proxy to connect to external world. +// Precedence will be the environment variables, followed by the config. +#[allow(missing_docs)] +pub fn create_client( + proxy_config: &Proxy, + client_certificate: Option<masking::Secret<String>>, + client_certificate_key: Option<masking::Secret<String>>, +) -> CustomResult<reqwest::Client, HttpClientError> { + match (client_certificate, client_certificate_key) { + (Some(encoded_certificate), Some(encoded_certificate_key)) => { + let client_builder = get_client_builder(proxy_config)?; + + let identity = create_identity_from_certificate_and_key( + encoded_certificate.clone(), + encoded_certificate_key, + )?; + let certificate_list = create_certificate(encoded_certificate)?; + let client_builder = certificate_list + .into_iter() + .fold(client_builder, |client_builder, certificate| { + client_builder.add_root_certificate(certificate) + }); + client_builder + .identity(identity) + .use_rustls_tls() + .build() + .change_context(HttpClientError::ClientConstructionFailed) + .attach_printable("Failed to construct client with certificate and certificate key") + } + _ => get_base_client(proxy_config), + } +} + +#[allow(missing_docs)] +pub fn get_client_builder( + proxy_config: &Proxy, +) -> CustomResult<reqwest::ClientBuilder, HttpClientError> { + let mut client_builder = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .pool_idle_timeout(Duration::from_secs( + proxy_config + .idle_pool_connection_timeout + .unwrap_or_default(), + )); + + let proxy_exclusion_config = + reqwest::NoProxy::from_string(&proxy_config.bypass_proxy_hosts.clone().unwrap_or_default()); + + // Proxy all HTTPS traffic through the configured HTTPS proxy + if let Some(url) = proxy_config.https_url.as_ref() { + client_builder = client_builder.proxy( + reqwest::Proxy::https(url) + .change_context(HttpClientError::InvalidProxyConfiguration) + .attach_printable("HTTPS proxy configuration error")? + .no_proxy(proxy_exclusion_config.clone()), + ); + } + + // Proxy all HTTP traffic through the configured HTTP proxy + if let Some(url) = proxy_config.http_url.as_ref() { + client_builder = client_builder.proxy( + reqwest::Proxy::http(url) + .change_context(HttpClientError::InvalidProxyConfiguration) + .attach_printable("HTTP proxy configuration error")? + .no_proxy(proxy_exclusion_config), + ); + } + + Ok(client_builder) +} + +#[allow(missing_docs)] +pub fn create_identity_from_certificate_and_key( + encoded_certificate: masking::Secret<String>, + encoded_certificate_key: masking::Secret<String>, +) -> Result<reqwest::Identity, error_stack::Report<HttpClientError>> { + let decoded_certificate = BASE64_ENGINE + .decode(encoded_certificate.expose()) + .change_context(HttpClientError::CertificateDecodeFailed)?; + + let decoded_certificate_key = BASE64_ENGINE + .decode(encoded_certificate_key.expose()) + .change_context(HttpClientError::CertificateDecodeFailed)?; + + let certificate = String::from_utf8(decoded_certificate) + .change_context(HttpClientError::CertificateDecodeFailed)?; + + let certificate_key = String::from_utf8(decoded_certificate_key) + .change_context(HttpClientError::CertificateDecodeFailed)?; + + let key_chain = format!("{}{}", certificate_key, certificate); + reqwest::Identity::from_pem(key_chain.as_bytes()) + .change_context(HttpClientError::CertificateDecodeFailed) +} + +#[allow(missing_docs)] +pub fn create_certificate( + encoded_certificate: masking::Secret<String>, +) -> Result<Vec<reqwest::Certificate>, error_stack::Report<HttpClientError>> { + let decoded_certificate = BASE64_ENGINE + .decode(encoded_certificate.expose()) + .change_context(HttpClientError::CertificateDecodeFailed)?; + + let certificate = String::from_utf8(decoded_certificate) + .change_context(HttpClientError::CertificateDecodeFailed)?; + reqwest::Certificate::from_pem_bundle(certificate.as_bytes()) + .change_context(HttpClientError::CertificateDecodeFailed) +} + +fn get_base_client(proxy_config: &Proxy) -> CustomResult<reqwest::Client, HttpClientError> { + Ok(DEFAULT_CLIENT + .get_or_try_init(|| { + get_client_builder(proxy_config)? + .build() + .change_context(HttpClientError::ClientConstructionFailed) + .attach_printable("Failed to construct base client") + })? + .clone()) +} diff --git a/crates/external_services/src/http_client/metrics.rs b/crates/external_services/src/http_client/metrics.rs new file mode 100644 index 00000000000..5b6f48334f2 --- /dev/null +++ b/crates/external_services/src/http_client/metrics.rs @@ -0,0 +1,9 @@ +use router_env::{counter_metric, global_meter, histogram_metric_f64}; + +global_meter!(GLOBAL_METER, "ROUTER_API"); + +counter_metric!(REQUEST_BUILD_FAILURE, GLOBAL_METER); + +histogram_metric_f64!(EXTERNAL_REQUEST_TIME, GLOBAL_METER); + +counter_metric!(AUTO_RETRY_CONNECTION_CLOSED, GLOBAL_METER); diff --git a/crates/external_services/src/http_client/request.rs b/crates/external_services/src/http_client/request.rs new file mode 100644 index 00000000000..cf2727f0668 --- /dev/null +++ b/crates/external_services/src/http_client/request.rs @@ -0,0 +1,45 @@ +use std::str::FromStr; + +use common_utils::request::Headers; +pub use common_utils::{errors::CustomResult, request::ContentType}; +use error_stack::ResultExt; +use hyperswitch_interfaces::errors::HttpClientError; +pub use masking::{Mask, Maskable}; +use router_env::{instrument, tracing}; + +#[allow(missing_docs)] +pub trait HeaderExt { + fn construct_header_map(self) -> CustomResult<reqwest::header::HeaderMap, HttpClientError>; +} + +impl HeaderExt for Headers { + fn construct_header_map(self) -> CustomResult<reqwest::header::HeaderMap, HttpClientError> { + use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; + + self.into_iter().try_fold( + HeaderMap::new(), + |mut header_map, (header_name, header_value)| { + let header_name = HeaderName::from_str(&header_name) + .change_context(HttpClientError::HeaderMapConstructionFailed)?; + let header_value = header_value.into_inner(); + let header_value = HeaderValue::from_str(&header_value) + .change_context(HttpClientError::HeaderMapConstructionFailed)?; + header_map.append(header_name, header_value); + Ok(header_map) + }, + ) + } +} + +#[allow(missing_docs)] +pub trait RequestBuilderExt { + fn add_headers(self, headers: reqwest::header::HeaderMap) -> Self; +} + +impl RequestBuilderExt for reqwest::RequestBuilder { + #[instrument(skip_all)] + fn add_headers(mut self, headers: reqwest::header::HeaderMap) -> Self { + self = self.headers(headers); + self + } +} diff --git a/crates/external_services/src/hubspot_proxy.rs b/crates/external_services/src/hubspot_proxy.rs new file mode 100644 index 00000000000..17817676410 --- /dev/null +++ b/crates/external_services/src/hubspot_proxy.rs @@ -0,0 +1,78 @@ +use masking::Secret; + +/// Lead source constant for Hubspot +pub const HUBSPOT_LEAD_SOURCE: &str = "Hyperswitch Dashboard"; + +/// Struct representing a request to Hubspot +#[derive(Clone, Debug, serde::Serialize, Default)] +pub struct HubspotRequest { + /// Indicates whether Hubspot should be used. + #[serde(rename = "useHubspot")] + pub use_hubspot: bool, + + /// The country of the user or company. + pub country: String, + + /// The ID of the Hubspot form being submitted. + #[serde(rename = "hubspotFormId")] + pub hubspot_form_id: String, + + /// The first name of the user. + pub firstname: Secret<String>, + + /// The last name of the user. + pub lastname: Secret<String>, + + /// The email address of the user. + pub email: Secret<String>, + + /// The name of the company. + #[serde(rename = "companyName")] + pub company_name: String, + + /// The source of the lead, typically set to "Hyperswitch Dashboard". + pub lead_source: String, + + /// The website URL of the company. + pub website: String, + + /// The phone number of the user. + pub phone: Secret<String>, + + /// The role or designation of the user. + pub role: String, + + /// The monthly GMV (Gross Merchandise Value) of the company. + #[serde(rename = "monthlyGMV")] + pub monthly_gmv: String, + + /// Notes from the business development team. + pub bd_notes: String, + + /// Additional message or comments. + pub message: String, +} + +#[allow(missing_docs)] +impl HubspotRequest { + pub fn new( + country: String, + hubspot_form_id: String, + firstname: Secret<String>, + email: Secret<String>, + company_name: String, + website: String, + ) -> Self { + Self { + use_hubspot: true, + country, + hubspot_form_id, + firstname, + email, + company_name, + lead_source: HUBSPOT_LEAD_SOURCE.to_string(), + website, + ..Default::default() + } + } +} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index 304ce248317..f3b1b330e16 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -17,8 +17,17 @@ pub mod no_encryption; /// Building grpc clients to communicate with the server pub mod grpc_client; +/// http_client module +pub mod http_client; + +/// hubspot_proxy module +pub mod hubspot_proxy; + pub mod managers; +/// crm module +pub mod crm; + /// Crate specific constants #[cfg(feature = "aws_kms")] pub mod consts { diff --git a/crates/hyperswitch_interfaces/src/crm.rs b/crates/hyperswitch_interfaces/src/crm.rs new file mode 100644 index 00000000000..40eb56e9e6b --- /dev/null +++ b/crates/hyperswitch_interfaces/src/crm.rs @@ -0,0 +1,69 @@ +use common_enums::CountryAlpha2; +use common_utils::{ + errors::CustomResult, + request::{Request, RequestContent}, +}; +use masking::Secret; + +use super::types::Proxy; +use crate::errors::HttpClientError; + +/// Crm Payload structure +#[derive(Clone, Debug, serde::Serialize, Default)] +pub struct CrmPayload { + /// The legal name of the business. + pub legal_business_name: Option<String>, + + /// A label or tag associated with the business. + pub business_label: Option<String>, + + /// The location of the business, represented as a country code (ISO Alpha-2 format). + pub business_location: Option<CountryAlpha2>, + + /// The display name of the business. + pub display_name: Option<String>, + + /// The email address of the point of contact (POC) for the business. + pub poc_email: Option<Secret<String>>, + + /// The type of business (e.g., LLC, Corporation, etc.). + pub business_type: Option<String>, + + /// A unique identifier for the business. + pub business_identifier: Option<String>, + + /// The website URL of the business. + pub business_website: Option<String>, + + /// The name of the point of contact (POC) for the business. + pub poc_name: Option<Secret<String>>, + + /// The contact number of the point of contact (POC) for the business. + pub poc_contact: Option<Secret<String>>, + + /// Additional comments or notes about the business. + pub comments: Option<String>, + + /// Indicates whether the Crm process for the business is completed. + pub is_completed: bool, + + /// The name of the country where the business is located. + pub business_country_name: Option<String>, +} + +/// Trait defining the interface for encryption management +#[async_trait::async_trait] +pub trait CrmInterface: Send + Sync { + /// Make body for the request + async fn make_body(&self, details: CrmPayload) -> RequestContent; + + /// Encrypt the given input data + async fn make_request(&self, body: RequestContent, origin_base_url: String) -> Request; + + /// Decrypt the given input data + async fn send_request( + &self, + proxy: &Proxy, + request: Request, + ) -> CustomResult<reqwest::Response, HttpClientError>; +} diff --git a/crates/hyperswitch_interfaces/src/errors.rs b/crates/hyperswitch_interfaces/src/errors.rs index 466186ae368..1a11c2d761d 100644 --- a/crates/hyperswitch_interfaces/src/errors.rs +++ b/crates/hyperswitch_interfaces/src/errors.rs @@ -1,5 +1,6 @@ //! Errors interface +use common_enums::ApiClientError; use common_utils::errors::ErrorSwitch; use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; @@ -156,3 +157,73 @@ impl ErrorSwitch<ApiErrorResponse> for ConnectorError { } } } + +// http client errors +#[allow(missing_docs, missing_debug_implementations)] +#[derive(Debug, Clone, thiserror::Error, PartialEq)] +pub enum HttpClientError { + #[error("Header map construction failed")] + HeaderMapConstructionFailed, + #[error("Invalid proxy configuration")] + InvalidProxyConfiguration, + #[error("Client construction failed")] + ClientConstructionFailed, + #[error("Certificate decode failed")] + CertificateDecodeFailed, + #[error("Request body serialization failed")] + BodySerializationFailed, + #[error("Unexpected state reached/Invariants conflicted")] + UnexpectedState, + + #[error("Failed to parse URL")] + UrlParsingFailed, + #[error("URL encoding of request payload failed")] + UrlEncodingFailed, + #[error("Failed to send request to connector {0}")] + RequestNotSent(String), + #[error("Failed to decode response")] + ResponseDecodingFailed, + + #[error("Server responded with Request Timeout")] + RequestTimeoutReceived, + + #[error("connection closed before a message could complete")] + ConnectionClosedIncompleteMessage, + + #[error("Server responded with Internal Server Error")] + InternalServerErrorReceived, + #[error("Server responded with Bad Gateway")] + BadGatewayReceived, + #[error("Server responded with Service Unavailable")] + ServiceUnavailableReceived, + #[error("Server responded with Gateway Timeout")] + GatewayTimeoutReceived, + #[error("Server responded with unexpected response")] + UnexpectedServerResponse, +} + +impl ErrorSwitch<ApiClientError> for HttpClientError { + fn switch(&self) -> ApiClientError { + match self { + Self::HeaderMapConstructionFailed => ApiClientError::HeaderMapConstructionFailed, + Self::InvalidProxyConfiguration => ApiClientError::InvalidProxyConfiguration, + Self::ClientConstructionFailed => ApiClientError::ClientConstructionFailed, + Self::CertificateDecodeFailed => ApiClientError::CertificateDecodeFailed, + Self::BodySerializationFailed => ApiClientError::BodySerializationFailed, + Self::UnexpectedState => ApiClientError::UnexpectedState, + Self::UrlParsingFailed => ApiClientError::UrlParsingFailed, + Self::UrlEncodingFailed => ApiClientError::UrlEncodingFailed, + Self::RequestNotSent(reason) => ApiClientError::RequestNotSent(reason.clone()), + Self::ResponseDecodingFailed => ApiClientError::ResponseDecodingFailed, + Self::RequestTimeoutReceived => ApiClientError::RequestTimeoutReceived, + Self::ConnectionClosedIncompleteMessage => { + ApiClientError::ConnectionClosedIncompleteMessage + } + Self::InternalServerErrorReceived => ApiClientError::InternalServerErrorReceived, + Self::BadGatewayReceived => ApiClientError::BadGatewayReceived, + Self::ServiceUnavailableReceived => ApiClientError::ServiceUnavailableReceived, + Self::GatewayTimeoutReceived => ApiClientError::GatewayTimeoutReceived, + Self::UnexpectedServerResponse => ApiClientError::UnexpectedServerResponse, + } + } +} diff --git a/crates/hyperswitch_interfaces/src/lib.rs b/crates/hyperswitch_interfaces/src/lib.rs index a9eb2997c89..b9c16f6d82f 100644 --- a/crates/hyperswitch_interfaces/src/lib.rs +++ b/crates/hyperswitch_interfaces/src/lib.rs @@ -23,3 +23,6 @@ pub mod metrics; pub mod secrets_interface; pub mod types; pub mod webhooks; + +/// Crm interface +pub mod crm; diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index 27f50609da2..e41e8cd9bcf 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -282,3 +282,31 @@ pub type BillingConnectorInvoiceSyncTypeV2 = dyn ConnectorIntegrationV2< BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, >; + +/// Proxy configuration structure +#[derive(Debug, serde::Deserialize, Clone)] +#[serde(default)] +pub struct Proxy { + /// The URL of the HTTP proxy server. + pub http_url: Option<String>, + + /// The URL of the HTTPS proxy server. + pub https_url: Option<String>, + + /// The timeout duration (in seconds) for idle connections in the proxy pool. + pub idle_pool_connection_timeout: Option<u64>, + + /// A comma-separated list of hosts that should bypass the proxy. + pub bypass_proxy_hosts: Option<String>, +} + +impl Default for Proxy { + fn default() -> Self { + Self { + http_url: Default::default(), + https_url: Default::default(), + idle_pool_connection_timeout: Some(90), + bypass_proxy_hosts: Default::default(), + } + } +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 30b520eb58b..5395e538c29 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -85,7 +85,6 @@ num-traits = "0.2.19" once_cell = "1.19.0" openidconnect = "3.5.0" # TODO: remove reqwest openssl = "0.10.70" -quick-xml = { version = "0.31.0", features = ["serialize"] } rand = "0.8.5" rand_chacha = "0.3.1" rdkafka = "0.36.2" diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index ac3a446b01f..dee7dfbb03c 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -49,18 +49,6 @@ impl Default for super::settings::Database { } } } - -impl Default for super::settings::Proxy { - fn default() -> Self { - Self { - http_url: Default::default(), - https_url: Default::default(), - idle_pool_connection_timeout: Some(90), - bypass_proxy_hosts: Default::default(), - } - } -} - impl Default for super::settings::Locker { fn default() -> Self { Self { diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 3ae171545bc..308cbe417bb 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -525,6 +525,7 @@ pub(crate) async fn fetch_raw_secrets( decision: conf.decision, locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors, grpc_client: conf.grpc_client, + crm: conf.crm, #[cfg(feature = "v2")] cell_information: conf.cell_information, network_tokenization_supported_card_networks: conf diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index b0fd269bf79..f7120ff4545 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -13,6 +13,7 @@ use error_stack::ResultExt; #[cfg(feature = "email")] use external_services::email::EmailSettings; use external_services::{ + crm::CrmManagerConfig, file_storage::FileStorageConfig, grpc_client::GrpcClientSettings, managers::{ @@ -21,8 +22,11 @@ use external_services::{ }, }; pub use hyperswitch_interfaces::configs::Connectors; -use hyperswitch_interfaces::secrets_interface::secret_state::{ - RawSecret, SecretState, SecretStateContainer, SecuredSecret, +use hyperswitch_interfaces::{ + secrets_interface::secret_state::{ + RawSecret, SecretState, SecretStateContainer, SecuredSecret, + }, + types::Proxy, }; use masking::Secret; pub use payment_methods::configs::settings::{ @@ -96,6 +100,7 @@ pub struct Settings<S: SecretState> { #[cfg(feature = "email")] pub email: EmailSettings, pub user: UserSettings, + pub crm: CrmManagerConfig, pub cors: CorsSettings, pub mandates: Mandates, pub zero_mandates: ZeroMandates, @@ -714,15 +719,6 @@ pub struct Jwekey { pub tunnel_private_key: Secret<String>, } -#[derive(Debug, Deserialize, Clone)] -#[serde(default)] -pub struct Proxy { - pub http_url: Option<String>, - pub https_url: Option<String>, - pub idle_pool_connection_timeout: Option<u64>, - pub bypass_proxy_hosts: Option<String>, -} - #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Server { @@ -988,6 +984,10 @@ impl Settings<SecuredSecret> { .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; + self.crm + .validate() + .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; + self.lock_settings.validate()?; self.events.validate()?; diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 43041ef01b6..f728e6aedc8 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -54,7 +54,6 @@ pub(crate) const API_KEY_LENGTH: usize = 64; // OID (Object Identifier) for the merchant ID field extension. pub(crate) const MERCHANT_ID_FIELD_EXTENSION_ID: &str = "1.2.840.113635.100.6.32"; -pub(crate) const METRICS_HOST_TAG_NAME: &str = "host"; pub const MAX_ROUTING_CONFIGS_PER_MERCHANT: usize = 100; pub const ROUTING_CONFIG_ID_LENGTH: usize = 10; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 27c8a9fb8ff..694bfe08cb9 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -15,6 +15,7 @@ use diesel_models::configs; #[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))] use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge}; use error_stack::{report, FutureExt, ResultExt}; +use external_services::http_client::client; use hyperswitch_domain_models::merchant_connector_account::{ FromRequestEncryptableMerchantConnectorAccount, UpdateEncryptableMerchantConnectorAccount, }; @@ -39,7 +40,7 @@ use crate::{ routes::{metrics, SessionState}, services::{ self, - api::{self as service_api, client}, + api::{self as service_api}, authentication, pm_auth as payment_initiation_service, }, types::{ diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs index 98aef1e3064..407f62f1ec9 100644 --- a/crates/router/src/core/connector_onboarding/paypal.rs +++ b/crates/router/src/core/connector_onboarding/paypal.rs @@ -1,6 +1,7 @@ use api_models::{admin::MerchantConnectorUpdate, connector_onboarding as api}; use common_utils::ext_traits::Encode; use error_stack::ResultExt; +pub use external_services::http_client; use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{ @@ -8,7 +9,7 @@ use crate::{ admin, errors::{ApiErrorResponse, RouterResult}, }, - services::{send_request, ApplicationResponse, Request}, + services::{ApplicationResponse, Request}, types::{self as oss_types, api as oss_api_types, api::connector_onboarding as types}, utils::connector_onboarding as utils, SessionState, @@ -47,7 +48,7 @@ pub async fn get_action_url_from_paypal( return_url, )) .await?; - let referral_response = send_request(&state, referral_request, None) + let referral_response = http_client::send_request(&state.conf.proxy, referral_request, None) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to send request to paypal referrals")?; @@ -97,10 +98,11 @@ pub async fn sync_merchant_onboarding_status( let merchant_details_request = utils::paypal::build_paypal_get_request(merchant_details_url, access_token.token.expose())?; - let merchant_details_response = send_request(&state, merchant_details_request, None) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to send request to paypal merchant details")?; + let merchant_details_response = + http_client::send_request(&state.conf.proxy, merchant_details_request, None) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to send request to paypal merchant details")?; let parsed_response: types::paypal::SellerStatusDetailsResponse = merchant_details_response .json() @@ -121,10 +123,11 @@ async fn find_paypal_merchant_by_tracking_id( merchant_onboarding_status_url(state.clone(), tracking_id), access_token.token.peek().to_string(), )?; - let seller_status_response = send_request(&state, seller_status_request, None) - .await - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable("Failed to send request to paypal onboarding status")?; + let seller_status_response = + http_client::send_request(&state.conf.proxy, seller_status_request, None) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to send request to paypal onboarding status")?; if seller_status_response.status().is_success() { return Ok(Some( diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs index 17e86dc41ca..16418ad83a9 100644 --- a/crates/router/src/core/recon.rs +++ b/crates/router/src/core/recon.rs @@ -17,6 +17,7 @@ use crate::{ storage, transformers::ForeignTryFrom, }, + utils::user as user_utils, SessionState, }; @@ -80,7 +81,7 @@ pub async fn send_recon_request( state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -211,7 +212,7 @@ pub async fn recon_merchant_account_update( let _ = state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 9802edfd346..1097f57b198 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -32,8 +32,6 @@ use user_api::dashboard_metadata::SetMetaDataRequest; #[cfg(feature = "v1")] use super::admin; use super::errors::{StorageErrorExt, UserErrors, UserResponse, UserResult}; -#[cfg(feature = "email")] -use crate::services::email::types as email_types; #[cfg(feature = "v1")] use crate::types::transformers::ForeignFrom; use crate::{ @@ -51,6 +49,8 @@ use crate::{ user::{theme as theme_utils, two_factor_auth as tfa_utils}, }, }; +#[cfg(feature = "email")] +use crate::{services::email::types as email_types, utils::user as user_utils}; pub mod dashboard_metadata; #[cfg(feature = "dummy_connector")] @@ -99,7 +99,7 @@ pub async fn signup_with_merchant_id( let send_email_result = state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -319,7 +319,7 @@ pub async fn connect_account( let send_email_result = state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -374,7 +374,7 @@ pub async fn connect_account( let magic_link_result = state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(magic_link_email), state.conf.proxy.https_url.as_ref(), ) @@ -390,7 +390,7 @@ pub async fn connect_account( let welcome_email_result = state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(welcome_to_community_email), state.conf.proxy.https_url.as_ref(), ) @@ -525,7 +525,7 @@ pub async fn forgot_password( state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -937,7 +937,7 @@ async fn handle_existing_user_invitation( is_email_sent = state .email_client .compose_and_send_email( - email_types::get_base_url(state), + user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -1092,7 +1092,7 @@ async fn handle_new_user_invitation( let send_email_result = state .email_client .compose_and_send_email( - email_types::get_base_url(state), + user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -1247,7 +1247,7 @@ pub async fn resend_invite( state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -1967,7 +1967,7 @@ pub async fn send_verification_mail( state .email_client .compose_and_send_email( - email_types::get_base_url(&state), + user_utils::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index a4068fc4fad..ece4c601694 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -8,10 +8,10 @@ use diesel_models::{ enums::DashboardMetadata as DBEnum, user::dashboard_metadata::DashboardMetadata, }; use error_stack::{report, ResultExt}; +use hyperswitch_interfaces::crm::CrmPayload; #[cfg(feature = "email")] use masking::ExposeInterface; use masking::PeekInterface; -#[cfg(feature = "email")] use router_env::logger; use crate::{ @@ -19,7 +19,7 @@ use crate::{ routes::{app::ReqState, SessionState}, services::{authentication::UserFromToken, ApplicationResponse}, types::domain::{self, user::dashboard_metadata as types, MerchantKeyStore}, - utils::user::dashboard_metadata as utils, + utils::user::{self as user_utils, dashboard_metadata as utils}, }; #[cfg(feature = "email")] use crate::{services::email::types as email_types, utils::user::theme as theme_utils}; @@ -501,7 +501,7 @@ async fn insert_metadata( .await?; let email_contents = email_types::BizEmailProd::new( state, - data, + data.clone(), theme.as_ref().map(|theme| theme.theme_id.clone()), theme .map(|theme| theme.email_config()) @@ -510,7 +510,7 @@ async fn insert_metadata( let send_email_result = state .email_client .compose_and_send_email( - email_types::get_base_url(state), + user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -519,6 +519,43 @@ async fn insert_metadata( } } + // Hubspot integration + let hubspot_body = state + .crm_client + .make_body(CrmPayload { + legal_business_name: data.legal_business_name, + business_label: data.business_label, + business_location: data.business_location, + display_name: data.display_name, + poc_email: data.poc_email, + business_type: data.business_type, + business_identifier: data.business_identifier, + business_website: data.business_website, + poc_name: data.poc_name, + poc_contact: data.poc_contact, + comments: data.comments, + is_completed: data.is_completed, + business_country_name: data.business_country_name, + }) + .await; + let base_url = user_utils::get_base_url(state); + let hubspot_request = state + .crm_client + .make_request(hubspot_body, base_url.to_string()) + .await; + + let _ = state + .crm_client + .send_request(&state.conf.proxy, hubspot_request) + .await + .inspect_err(|err| { + logger::error!( + "An error occurred while sending data to hubspot for user_id {}: {:?}", + user.user_id, + err + ); + }); + metadata } types::MetaData::SPTestPayment(data) => { diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9cb83192f6f..82a91f468c5 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -17,6 +17,7 @@ use external_services::{ grpc_client::{GrpcClients, GrpcHeaders}, }; use hyperswitch_interfaces::{ + crm::CrmInterface, encryption_interface::EncryptionManagementInterface, secrets_interface::secret_state::{RawSecret, SecuredSecret}, }; @@ -124,6 +125,7 @@ pub struct SessionState { pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, pub locale: String, + pub crm_client: Arc<dyn CrmInterface>, } impl scheduler::SchedulerSessionState for SessionState { fn get_db(&self) -> Box<dyn SchedulerInterface> { @@ -235,6 +237,7 @@ pub struct AppState { pub encryption_client: Arc<dyn EncryptionManagementInterface>, pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, + pub crm_client: Arc<dyn CrmInterface>, } impl scheduler::SchedulerAppState for AppState { fn get_tenants(&self) -> Vec<id_type::TenantId> { @@ -396,6 +399,7 @@ impl AppState { let file_storage_client = conf.file_storage.get_file_storage_client().await; let theme_storage_client = conf.theme.storage.get_file_storage_client().await; + let crm_client = conf.crm.get_crm_client().await; let grpc_client = conf.grpc_client.get_grpc_client_interface().await; @@ -418,6 +422,7 @@ impl AppState { encryption_client, grpc_client, theme_storage_client, + crm_client, } }) .await @@ -511,6 +516,7 @@ impl AppState { grpc_client: Arc::clone(&self.grpc_client), theme_storage_client: self.theme_storage_client.clone(), locale: locale.unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string()), + crm_client: self.crm_client.clone(), }) } } diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 63ef0b876f3..e8aeef3e406 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -11,7 +11,6 @@ counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses // API Level Metrics counter_metric!(REQUESTS_RECEIVED, GLOBAL_METER); histogram_metric_f64!(REQUEST_TIME, GLOBAL_METER); -histogram_metric_f64!(EXTERNAL_REQUEST_TIME, GLOBAL_METER); // Operation Level Metrics counter_metric!(PAYMENT_OPS_COUNT, GLOBAL_METER); @@ -99,7 +98,6 @@ counter_metric!(APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT, GLOBAL_METER); counter_metric!(APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT, GLOBAL_METER); // Metrics for Payment Auto Retries -counter_metric!(AUTO_RETRY_CONNECTION_CLOSED, GLOBAL_METER); counter_metric!(AUTO_RETRY_ELIGIBLE_REQUEST_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_GSM_MISS_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_GSM_FETCH_FAILURE_COUNT, GLOBAL_METER); diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index a9193160263..3fef01a8c21 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -3,7 +3,6 @@ pub mod generic_link_response; pub mod request; use std::{ collections::{HashMap, HashSet}, - error::Error, fmt::Debug, future::Future, str, @@ -52,7 +51,6 @@ use serde::Serialize; use serde_json::json; use tera::{Context, Error as TeraError, Tera}; -use self::request::{HeaderExt, RequestBuilderExt}; use super::{ authentication::AuthenticateAndFetch, connector_integration_interface::BoxedConnectorIntegrationInterface, @@ -431,178 +429,6 @@ pub async fn call_connector_api( handle_response(response).await } -#[instrument(skip_all)] -pub async fn send_request( - state: &SessionState, - request: Request, - option_timeout_secs: Option<u64>, -) -> CustomResult<reqwest::Response, errors::ApiClientError> { - logger::info!(method=?request.method, headers=?request.headers, payload=?request.body, ?request); - - let url = - url::Url::parse(&request.url).change_context(errors::ApiClientError::UrlParsingFailed)?; - - let client = client::create_client( - &state.conf.proxy, - request.certificate, - request.certificate_key, - )?; - - let headers = request.headers.construct_header_map()?; - let metrics_tag = router_env::metric_attributes!(( - consts::METRICS_HOST_TAG_NAME, - url.host_str().unwrap_or_default().to_owned() - )); - let request = { - match request.method { - Method::Get => client.get(url), - Method::Post => { - let client = client.post(url); - match request.body { - Some(RequestContent::Json(payload)) => client.json(&payload), - Some(RequestContent::FormData(form)) => client.multipart(form), - Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload), - Some(RequestContent::Xml(payload)) => { - let body = quick_xml::se::to_string(&payload) - .change_context(errors::ApiClientError::BodySerializationFailed)?; - client.body(body).header("Content-Type", "application/xml") - } - Some(RequestContent::RawBytes(payload)) => client.body(payload), - None => client, - } - } - Method::Put => { - let client = client.put(url); - match request.body { - Some(RequestContent::Json(payload)) => client.json(&payload), - Some(RequestContent::FormData(form)) => client.multipart(form), - Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload), - Some(RequestContent::Xml(payload)) => { - let body = quick_xml::se::to_string(&payload) - .change_context(errors::ApiClientError::BodySerializationFailed)?; - client.body(body).header("Content-Type", "application/xml") - } - Some(RequestContent::RawBytes(payload)) => client.body(payload), - None => client, - } - } - Method::Patch => { - let client = client.patch(url); - match request.body { - Some(RequestContent::Json(payload)) => client.json(&payload), - Some(RequestContent::FormData(form)) => client.multipart(form), - Some(RequestContent::FormUrlEncoded(payload)) => client.form(&payload), - Some(RequestContent::Xml(payload)) => { - let body = quick_xml::se::to_string(&payload) - .change_context(errors::ApiClientError::BodySerializationFailed)?; - client.body(body).header("Content-Type", "application/xml") - } - Some(RequestContent::RawBytes(payload)) => client.body(payload), - None => client, - } - } - Method::Delete => client.delete(url), - } - .add_headers(headers) - .timeout(Duration::from_secs( - option_timeout_secs.unwrap_or(consts::REQUEST_TIME_OUT), - )) - }; - - // We cannot clone the request type, because it has Form trait which is not cloneable. So we are cloning the request builder here. - let cloned_send_request = request.try_clone().map(|cloned_request| async { - cloned_request - .send() - .await - .map_err(|error| match error { - error if error.is_timeout() => { - metrics::REQUEST_BUILD_FAILURE.add(1, &[]); - errors::ApiClientError::RequestTimeoutReceived - } - error if is_connection_closed_before_message_could_complete(&error) => { - metrics::REQUEST_BUILD_FAILURE.add(1, &[]); - errors::ApiClientError::ConnectionClosedIncompleteMessage - } - _ => errors::ApiClientError::RequestNotSent(error.to_string()), - }) - .attach_printable("Unable to send request to connector") - }); - - let send_request = async { - request - .send() - .await - .map_err(|error| match error { - error if error.is_timeout() => { - metrics::REQUEST_BUILD_FAILURE.add(1, &[]); - errors::ApiClientError::RequestTimeoutReceived - } - error if is_connection_closed_before_message_could_complete(&error) => { - metrics::REQUEST_BUILD_FAILURE.add(1, &[]); - errors::ApiClientError::ConnectionClosedIncompleteMessage - } - _ => errors::ApiClientError::RequestNotSent(error.to_string()), - }) - .attach_printable("Unable to send request to connector") - }; - - let response = common_utils::metrics::utils::record_operation_time( - send_request, - &metrics::EXTERNAL_REQUEST_TIME, - metrics_tag, - ) - .await; - // Retry once if the response is connection closed. - // - // This is just due to the racy nature of networking. - // hyper has a connection pool of idle connections, and it selected one to send your request. - // Most of the time, hyper will receive the server’s FIN and drop the dead connection from its pool. - // But occasionally, a connection will be selected from the pool - // and written to at the same time the server is deciding to close the connection. - // Since hyper already wrote some of the request, - // it can’t really retry it automatically on a new connection, since the server may have acted already - match response { - Ok(response) => Ok(response), - Err(error) - if error.current_context() - == &errors::ApiClientError::ConnectionClosedIncompleteMessage => - { - metrics::AUTO_RETRY_CONNECTION_CLOSED.add(1, &[]); - match cloned_send_request { - Some(cloned_request) => { - logger::info!( - "Retrying request due to connection closed before message could complete" - ); - common_utils::metrics::utils::record_operation_time( - cloned_request, - &metrics::EXTERNAL_REQUEST_TIME, - metrics_tag, - ) - .await - } - None => { - logger::info!("Retrying request due to connection closed before message could complete failed as request is not cloneable"); - Err(error) - } - } - } - err @ Err(_) => err, - } -} - -fn is_connection_closed_before_message_could_complete(error: &reqwest::Error) -> bool { - let mut source = error.source(); - while let Some(err) = source { - if let Some(hyper_err) = err.downcast_ref::<hyper::Error>() { - if hyper_err.is_incomplete_message() { - return true; - } - } - source = err.source(); - } - false -} - #[instrument(skip_all)] async fn handle_response( response: CustomResult<reqwest::Response, errors::ApiClientError>, diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index 096c5ed45d1..d690ebd3277 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -1,139 +1,20 @@ use std::time::Duration; -use base64::Engine; +use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; +pub use external_services::http_client::{self, client}; use http::{HeaderValue, Method}; -use masking::{ExposeInterface, PeekInterface}; -use once_cell::sync::OnceCell; +use hyperswitch_interfaces::types::Proxy; +use masking::PeekInterface; use reqwest::multipart::Form; use router_env::tracing_actix_web::RequestId; use super::{request::Maskable, Request}; use crate::{ - configs::settings::Proxy, - consts::BASE64_ENGINE, core::errors::{ApiClientError, CustomResult}, routes::SessionState, }; -static DEFAULT_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); - -fn get_client_builder( - proxy_config: &Proxy, -) -> CustomResult<reqwest::ClientBuilder, ApiClientError> { - let mut client_builder = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .pool_idle_timeout(Duration::from_secs( - proxy_config - .idle_pool_connection_timeout - .unwrap_or_default(), - )); - - let proxy_exclusion_config = - reqwest::NoProxy::from_string(&proxy_config.bypass_proxy_hosts.clone().unwrap_or_default()); - - // Proxy all HTTPS traffic through the configured HTTPS proxy - if let Some(url) = proxy_config.https_url.as_ref() { - client_builder = client_builder.proxy( - reqwest::Proxy::https(url) - .change_context(ApiClientError::InvalidProxyConfiguration) - .attach_printable("HTTPS proxy configuration error")? - .no_proxy(proxy_exclusion_config.clone()), - ); - } - - // Proxy all HTTP traffic through the configured HTTP proxy - if let Some(url) = proxy_config.http_url.as_ref() { - client_builder = client_builder.proxy( - reqwest::Proxy::http(url) - .change_context(ApiClientError::InvalidProxyConfiguration) - .attach_printable("HTTP proxy configuration error")? - .no_proxy(proxy_exclusion_config), - ); - } - - Ok(client_builder) -} - -fn get_base_client(proxy_config: &Proxy) -> CustomResult<reqwest::Client, ApiClientError> { - Ok(DEFAULT_CLIENT - .get_or_try_init(|| { - get_client_builder(proxy_config)? - .build() - .change_context(ApiClientError::ClientConstructionFailed) - .attach_printable("Failed to construct base client") - })? - .clone()) -} - -// We may need to use outbound proxy to connect to external world. -// Precedence will be the environment variables, followed by the config. -pub fn create_client( - proxy_config: &Proxy, - client_certificate: Option<masking::Secret<String>>, - client_certificate_key: Option<masking::Secret<String>>, -) -> CustomResult<reqwest::Client, ApiClientError> { - match (client_certificate, client_certificate_key) { - (Some(encoded_certificate), Some(encoded_certificate_key)) => { - let client_builder = get_client_builder(proxy_config)?; - - let identity = create_identity_from_certificate_and_key( - encoded_certificate.clone(), - encoded_certificate_key, - )?; - let certificate_list = create_certificate(encoded_certificate)?; - let client_builder = certificate_list - .into_iter() - .fold(client_builder, |client_builder, certificate| { - client_builder.add_root_certificate(certificate) - }); - client_builder - .identity(identity) - .use_rustls_tls() - .build() - .change_context(ApiClientError::ClientConstructionFailed) - .attach_printable("Failed to construct client with certificate and certificate key") - } - _ => get_base_client(proxy_config), - } -} - -pub fn create_identity_from_certificate_and_key( - encoded_certificate: masking::Secret<String>, - encoded_certificate_key: masking::Secret<String>, -) -> Result<reqwest::Identity, error_stack::Report<ApiClientError>> { - let decoded_certificate = BASE64_ENGINE - .decode(encoded_certificate.expose()) - .change_context(ApiClientError::CertificateDecodeFailed)?; - - let decoded_certificate_key = BASE64_ENGINE - .decode(encoded_certificate_key.expose()) - .change_context(ApiClientError::CertificateDecodeFailed)?; - - let certificate = String::from_utf8(decoded_certificate) - .change_context(ApiClientError::CertificateDecodeFailed)?; - - let certificate_key = String::from_utf8(decoded_certificate_key) - .change_context(ApiClientError::CertificateDecodeFailed)?; - - let key_chain = format!("{}{}", certificate_key, certificate); - reqwest::Identity::from_pem(key_chain.as_bytes()) - .change_context(ApiClientError::CertificateDecodeFailed) -} - -pub fn create_certificate( - encoded_certificate: masking::Secret<String>, -) -> Result<Vec<reqwest::Certificate>, error_stack::Report<ApiClientError>> { - let decoded_certificate = BASE64_ENGINE - .decode(encoded_certificate.expose()) - .change_context(ApiClientError::CertificateDecodeFailed)?; - - let certificate = String::from_utf8(decoded_certificate) - .change_context(ApiClientError::CertificateDecodeFailed)?; - reqwest::Certificate::from_pem_bundle(certificate.as_bytes()) - .change_context(ApiClientError::CertificateDecodeFailed) -} - pub trait RequestBuilder: Send + Sync { fn json(&mut self, body: serde_json::Value); fn url_encoded_form(&mut self, body: serde_json::Value); @@ -196,7 +77,8 @@ pub struct ProxyClient { impl ProxyClient { pub fn new(proxy_config: &Proxy) -> CustomResult<Self, ApiClientError> { - let client = get_client_builder(proxy_config)? + let client = client::get_client_builder(proxy_config) + .switch()? .build() .change_context(ApiClientError::InvalidProxyConfiguration)?; Ok(Self { @@ -213,9 +95,10 @@ impl ProxyClient { ) -> CustomResult<reqwest::Client, ApiClientError> { match (client_certificate, client_certificate_key) { (Some(certificate), Some(certificate_key)) => { - let client_builder = get_client_builder(&self.proxy_config)?; + let client_builder = client::get_client_builder(&self.proxy_config).switch()?; let identity = - create_identity_from_certificate_and_key(certificate, certificate_key)?; + client::create_identity_from_certificate_and_key(certificate, certificate_key) + .switch()?; Ok(client_builder .identity(identity) .build() @@ -314,7 +197,9 @@ impl ApiClient for ProxyClient { option_timeout_secs: Option<u64>, _forward_to_kafka: bool, ) -> CustomResult<reqwest::Response, ApiClientError> { - crate::services::send_request(state, request, option_timeout_secs).await + http_client::send_request(&state.conf.proxy, request, option_timeout_secs) + .await + .switch() } fn add_request_id(&mut self, request_id: RequestId) { diff --git a/crates/router/src/services/api/request.rs b/crates/router/src/services/api/request.rs index ed53da0d971..7cf35ff0d87 100644 --- a/crates/router/src/services/api/request.rs +++ b/crates/router/src/services/api/request.rs @@ -1,48 +1,2 @@ -use std::str::FromStr; - pub use common_utils::request::ContentType; -use common_utils::request::Headers; -use error_stack::ResultExt; pub use masking::{Mask, Maskable}; -use router_env::{instrument, tracing}; - -use crate::core::errors::{self, CustomResult}; - -pub(super) trait HeaderExt { - fn construct_header_map( - self, - ) -> CustomResult<reqwest::header::HeaderMap, errors::ApiClientError>; -} - -impl HeaderExt for Headers { - fn construct_header_map( - self, - ) -> CustomResult<reqwest::header::HeaderMap, errors::ApiClientError> { - use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; - - self.into_iter().try_fold( - HeaderMap::new(), - |mut header_map, (header_name, header_value)| { - let header_name = HeaderName::from_str(&header_name) - .change_context(errors::ApiClientError::HeaderMapConstructionFailed)?; - let header_value = header_value.into_inner(); - let header_value = HeaderValue::from_str(&header_value) - .change_context(errors::ApiClientError::HeaderMapConstructionFailed)?; - header_map.append(header_name, header_value); - Ok(header_map) - }, - ) - } -} - -pub(super) trait RequestBuilderExt { - fn add_headers(self, headers: reqwest::header::HeaderMap) -> Self; -} - -impl RequestBuilderExt for reqwest::RequestBuilder { - #[instrument(skip_all)] - fn add_headers(mut self, headers: reqwest::header::HeaderMap) -> Self { - self = self.headers(headers); - self - } -} diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 0328ea988d4..73c42818439 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -320,15 +320,6 @@ pub fn get_link_with_token( email_url } - -pub fn get_base_url(state: &SessionState) -> &str { - if !state.conf.multitenancy.enabled { - &state.conf.user.base_url - } else { - &state.tenant.user.control_center_url - } -} - pub struct VerifyEmail { pub recipient_email: domain::UserEmail, pub settings: std::sync::Arc<configs::Settings>, @@ -576,7 +567,7 @@ impl BizEmailProd { state.conf.email.prod_intent_recipient_email.clone(), )?, settings: state.conf.clone(), - user_name: data.poc_name.unwrap_or_default().into(), + user_name: data.poc_name.unwrap_or_default(), poc_email: data.poc_email.unwrap_or_default(), legal_business_name: data.legal_business_name.unwrap_or_default(), business_location: data diff --git a/crates/router/src/services/openidconnect.rs b/crates/router/src/services/openidconnect.rs index c4dd0df6e13..f9a76a0ada2 100644 --- a/crates/router/src/services/openidconnect.rs +++ b/crates/router/src/services/openidconnect.rs @@ -1,4 +1,6 @@ +use common_utils::errors::ErrorSwitch; use error_stack::ResultExt; +use external_services::http_client::client; use masking::{ExposeInterface, Secret}; use oidc::TokenResponse; use openidconnect::{self as oidc, core as oidc_core}; @@ -9,7 +11,6 @@ use crate::{ consts, core::errors::{UserErrors, UserResult}, routes::SessionState, - services::api::client, types::domain::user::UserEmail, }; @@ -156,7 +157,7 @@ async fn get_oidc_reqwest_client( request: oidc::HttpRequest, ) -> Result<oidc::HttpResponse, ApiClientError> { let client = client::create_client(&state.conf.proxy, None, None) - .map_err(|e| e.current_context().to_owned())?; + .map_err(|e| e.current_context().switch())?; let mut request_builder = client .request(request.method, request.url) diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index ea3edd8dfc7..18e227912ef 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -380,3 +380,11 @@ pub fn generate_env_specific_merchant_id(value: String) -> UserResult<id_type::M Ok(id_type::MerchantId::new_from_unix_timestamp()) } } + +pub fn get_base_url(state: &SessionState) -> &str { + if !state.conf.multitenancy.enabled { + &state.conf.user.base_url + } else { + &state.tenant.user.control_center_url + } +} diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index 4df78847b39..51e862681ae 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -9,9 +9,12 @@ use crate::{ consts, errors, logger::error, routes::{metrics, SessionState}, - services::email::types::{self as email_types, ApiKeyExpiryReminder}, + services::email::types::ApiKeyExpiryReminder, types::{api, domain::UserEmail, storage}, - utils::{user::theme as theme_utils, OptionExt}, + utils::{ + user::{self as user_utils, theme as theme_utils}, + OptionExt, + }, }; pub struct ApiKeyExpiryWorkflow; @@ -110,7 +113,7 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { .email_client .clone() .compose_and_send_email( - email_types::get_base_url(state), + user_utils::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), )
2025-04-11T12:48:38Z
## 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 includes - HubSpot proxy integration for `prod_intent` triggered from the dashboard - New CRM interface with two implementations: NoCrm and HubspotProxy. - Includes refactoring to move `http_client send_request` and `client` from the `router` module to `external_services` to support this integration. ### 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). --> Add hubspot tracking in dashboard prod intent ## 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)? --> Through dashboard FE - SIgnin in dashboard - Create a prod intent for a merchant - This will trigger hubspot tracking from BE and this should be visible in hubspot dashboard ## 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.114.0
1dabfe3e2c0d9b72e41a5bd61c5a394248b7997b
1dabfe3e2c0d9b72e41a5bd61c5a394248b7997b
juspay/hyperswitch
juspay__hyperswitch-7826
Bug: [CI]: remove private keys from configs
diff --git a/config/development.toml b/config/development.toml index 951cb44bd63..3a041db3574 100644 --- a/config/development.toml +++ b/config/development.toml @@ -106,35 +106,7 @@ aXXV1Z1wYUhlsO0jyd1bVvjyuE/KE1TbBS0gfR/RkacODmmE2zEdZ0EyyiXwqkmc oQIDAQAB -----END PUBLIC KEY----- """ -vault_private_key = """ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA5Z/K0JWds8iHhWCa+rj0rhOQX1nVs/ArQ1D0vh3UlSPR2vZU -TrkdP7i3amv4d2XDC+3+5/YWExTkpxqnfl1T9J37leN2guAARed6oYoTDEP/OoKt -nUrKK2xk/+V5DNOWcRiSpcCrJOOIEoACOlPIrXQSg16KDZQb0QTMntnsiPIJDbsO -GcdKytRAcNaokiKLnia1v13N3bk6dSplrj1YzawslZfgqD0eov4FjzBMoA19yNtl -VLLf6kOkLcFQjTKXJLP1tLflLUBPTg8fm9wgAPK2BjMQ2AMkUxx0ubbtw/9CeJ+b -FWrqGnEhlvfDMlyAV77sAiIdQ4mXs3TLcLb/AQIDAQABAoIBAGNekD1N0e5AZG1S -zh6cNb6zVrH8xV9WGtLJ0PAJJrrXwnQYT4m10DOIM0+Jo/+/ePXLq5kkRI9DZmPu -Q/eKWc+tInfN9LZUS6n0r3wCrZWMQ4JFlO5RtEWwZdDbtFPZqOwObz/treKL2JHw -9YXaRijR50UUf3e61YLRqd9AfX0RNuuG8H+WgU3Gwuh5TwRnljM3JGaDPHsf7HLS -tNkqJuByp26FEbOLTokZDbHN0sy7/6hufxnIS9AK4vp8y9mZAjghG26Rbg/H71mp -Z+Q6P1y7xdgAKbhq7usG3/o4Y1e9wnghHvFS7DPwGekHQH2+LsYNEYOir1iRjXxH -GUXOhfUCgYEA+cR9jONQFco8Zp6z0wdGlBeYoUHVMjThQWEblWL2j4RG/qQd/y0j -uhVeU0/PmkYK2mgcjrh/pgDTtPymc+QuxBi+lexs89ppuJIAgMvLUiJT67SBHguP -l4+oL9U78KGh7PfJpMKH+Pk5yc1xucAevk0wWmr5Tz2vKRDavFTPV+MCgYEA61qg -Y7yN0cDtxtqlZdMC8BJPFCQ1+s3uB0wetAY3BEKjfYc2O/4sMbixXzt5PkZqZy96 -QBUBxhcM/rIolpM3nrgN7h1nmJdk9ljCTjWoTJ6fDk8BUh8+0GrVhTbe7xZ+bFUN -UioIqvfapr/q/k7Ah2mCBE04wTZFry9fndrH2ssCgYEAh1T2Cj6oiAX6UEgxe2h3 -z4oxgz6efAO3AavSPFFQ81Zi+VqHflpA/3TQlSerfxXwj4LV5mcFkzbjfy9eKXE7 -/bjCm41tQ3vWyNEjQKYr1qcO/aniRBtThHWsVa6eObX6fOGN+p4E+txfeX693j3A -6q/8QSGxUERGAmRFgMIbTq0CgYAmuTeQkXKII4U75be3BDwEgg6u0rJq/L0ASF74 -4djlg41g1wFuZ4if+bJ9Z8ywGWfiaGZl6s7q59oEgg25kKljHQd1uTLVYXuEKOB3 -e86gJK0o7ojaGTf9lMZi779IeVv9uRTDAxWAA93e987TXuPAo/R3frkq2SIoC9Rg -paGidwKBgBqYd/iOJWsUZ8cWEhSE1Huu5rDEpjra8JPXHqQdILirxt1iCA5aEQou -BdDGaDr8sepJbGtjwTyiG8gEaX1DD+KsF2+dQRQdQfcYC40n8fKkvpFwrKjDj1ac -VuY3OeNxi+dC2r7HppP3O/MJ4gX/RJJfSrcaGP8/Ke1W5+jE97Qy ------END RSA PRIVATE KEY----- -""" +vault_private_key = "" tunnel_private_key = "" [connectors.supported]
2025-04-16T07:00:23Z
This PR removes the `vault_private_key` from the configs.
v1.113.0
9d1e0985a3e8df1e346005c1494c7cd44a5bd17f
9d1e0985a3e8df1e346005c1494c7cd44a5bd17f
juspay/hyperswitch
juspay__hyperswitch-7822
Bug: [FEATURE] : [CONNECTOR] Add globalpay, globepay, itaubank, nexinets, nuvei, prophetpay, zen in feature matrix Add globalpay, globepay, itaubank, nexinets, nuvei, prophetpay, zen connectors in feature matrix
diff --git a/config/config.example.toml b/config/config.example.toml index 51efc6c7087..96c081588d5 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -589,6 +589,7 @@ pix = { country = "BR", currency = "BRL" } red_compra = { country = "CL", currency = "CLP" } red_pagos = { country = "UY", currency = "UYU" } + [pm_filters.zsl] local_bank_transfer = { country = "CN", currency = "CNY" } @@ -607,13 +608,45 @@ google_pay = { currency = "USD,GBP,EUR,PLN" } samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } +[pm_filters.globepay] +ali_pay = { country = "GB",currency = "GBP" } +we_chat_pay = { country = "GB",currency = "GBP" } + + +[pm_filters.itaubank] +pix = { country = "BR", currency = "BRL" } + +[pm_filters.nexinets] +credit = { country = "DE",currency = "EUR" } +debit = { country = "DE",currency = "EUR" } +ideal = { country = "DE",currency = "EUR" } +giropay = { country = "DE",currency = "EUR" } +sofort = { country = "DE",currency = "EUR" } +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,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" } +google_pay = { 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" } +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" } + [pm_filters.stax] credit = { currency = "USD" } debit = { currency = "USD" } ach = { currency = "USD" } [pm_filters.prophetpay] -card_redirect = { currency = "USD" } +card_redirect = { country = "US", currency = "USD" } [pm_filters.payu] debit = { country = "AE, AF, AL, AM, CW, AO, AR, AU, AW, AZ, BA, BB, BG, BH, BI, BM, BN, BO, BR, BS, BW, BY, BZ, CA, CD, LI, CL, CN, CO, CR, CV, CZ, DJ, DK, DO, DZ, EG, ET, AD, FJ, FK, GG, GE, GH, GI, GM, GN, GT, GY, HK, HN, HR, HT, HU, ID, IL, IQ, IS, JM, JO, JP, KG, KH, KM, KR, KW, KY, KZ, LA, LB, LR, LS, MA, MD, MG, MK, MN, MO, MR, MV, MW, MX, MY, MZ, NA, NG, NI, BV, CK, OM, PA, PE, PG, PL, PY, QA, RO, RS, RW, SA, SB, SC, SE, SG, SH, SO, SR, SV, SZ, TH, TJ, TM, TN, TO, TR, TT, TW, TZ, UG, AS, UY, UZ, VE, VN, VU, WS, CM, AI, BJ, PF, YE, ZA, ZM, ZW", currency = "AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BWP, BYN, BZD, CAD, CDF, CHF, CLP, CNY, COP, CRC, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, IQD, ISK, JMD, JOD, JPY, KGS, KHR, KMF, KRW, KWD, KYD, KZT, LAK, LBP, LRD, LSL, MAD, MDL, MGA, MKD, MNT, MOP, MRU, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NZD, OMR, PAB, PEN, PGK, PLN, PYG, QAR, RON, RSD, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SOS, SRD, SVC, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 15bfe73ecab..5b2fafb07a9 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -348,8 +348,8 @@ ideal = { country = "NL", currency = "EUR" } sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } [pm_filters.globepay] -ali_pay.currency = "GBP,CNY" -we_chat_pay.currency = "GBP,CNY" +ali_pay = { country = "GB",currency = "GBP,CNY" } +we_chat_pay = { country = "GB",currency = "GBP,CNY" } [pm_filters.jpmorgan] debit = { country = "CA, GB, US, AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IE, IT, LV, LT, LU, MT, NL, PL, PT, RO, SK, SI, ES, SE", currency = "USD, EUR, GBP, AUD, NZD, SGD, CAD, JPY, HKD, KRW, TWD, MXN, BRL, DKK, NOK, ZAR, SEK, CHF, CZK, PLN, TRY, AFN, ALL, DZD, AOA, ARS, AMD, AWG, AZN, BSD, BDT, BBD, BYN, BZD, BMD, BOB, BAM, BWP, BND, BGN, BIF, BTN, XOF, XAF, XPF, KHR, CVE, KYD, CLP, CNY, COP, KMF, CDF, CRC, HRK, DJF, DOP, XCD, EGP, ETB, FKP, FJD, GMD, GEL, GHS, GIP, GTQ, GYD, HTG, HNL, HUF, ISK, INR, IDR, ILS, JMD, KZT, KES, LAK, LBP, LSL, LRD, MOP, MKD, MGA, MWK, MYR, MVR, MRU, MUR, MDL, MNT, MAD, MZN, MMK, NAD, NPR, ANG, PGK, NIO, NGN, PKR, PAB, PYG, PEN, PHP, QAR, RON, RWF, SHP, WST, STN, SAR, RSD, SCR, SLL, SBD, SOS, LKR, SRD, SZL, TJS, TZS, THB, TOP, TTD, UGX, UAH, AED, UYU, UZS, VUV, VND, YER, ZMW" } @@ -377,7 +377,7 @@ credit = { country = "AE, AF, AL, AM, CW, AO, AR, AU, AW, AZ, BA, BB, BG, BH, BI google_pay = { country = "AE, AF, AL, AM, CW, AO, AR, AU, AW, AZ, BA, BB, BG, BH, BI, BM, BN, BO, BR, BS, BW, BY, BZ, CA, CD, LI, CL, CN, CO, CR, CV, CZ, DJ, DK, DO, DZ, EG, ET, AD, FJ, FK, GG, GE, GH, GI, GM, GN, GT, GY, HK, HN, HR, HT, HU, ID, IL, IQ, IS, JM, JO, JP, KG, KH, KM, KR, KW, KY, KZ, LA, LB, LR, LS, MA, MD, MG, MK, MN, MO, MR, MV, MW, MX, MY, MZ, NA, NG, NI, BV, CK, OM, PA, PE, PG, PL, PY, QA, RO, RS, RW, SA, SB, SC, SE, SG, SH, SO, SR, SV, SZ, TH, TJ, TM, TN, TO, TR, TT, TW, TZ, UG, AS, UY, UZ, VE, VN, VU, WS, CM, AI, BJ, PF, YE, ZA, ZM, ZW", currency = "AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BWP, BYN, BZD, CAD, CDF, CHF, CLP, CNY, COP, CRC, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, IQD, ISK, JMD, JOD, JPY, KGS, KHR, KMF, KRW, KWD, KYD, KZT, LAK, LBP, LRD, LSL, MAD, MDL, MGA, MKD, MNT, MOP, MRU, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NZD, OMR, PAB, PEN, PGK, PLN, PYG, QAR, RON, RSD, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SOS, SRD, SVC, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL" } [pm_filters.prophetpay] -card_redirect.currency = "USD" +card_redirect = { country = "US", currency = "USD" } [pm_filters.stax] ach = { country = "US", currency = "USD" } @@ -403,6 +403,34 @@ google_pay = { currency = "USD,GBP,EUR,PLN" } samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } +[pm_filters.itaubank] +pix = { country = "BR", currency = "BRL" } + +[pm_filters.nexinets] +credit = { country = "DE",currency = "EUR" } +debit = { country = "DE",currency = "EUR" } +ideal = { country = "DE",currency = "EUR" } +giropay = { country = "DE",currency = "EUR" } +sofort = { country = "DE",currency = "EUR" } +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,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" } +google_pay = { 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" } +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" } + + [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 9d3273647f4..7fab1b39036 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -350,6 +350,34 @@ google_pay = { currency = "USD,GBP,EUR,PLN" } samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } +[pm_filters.itaubank] +pix = { country = "BR", currency = "BRL" } + +[pm_filters.nexinets] +credit = { country = "DE",currency = "EUR" } +debit = { country = "DE",currency = "EUR" } +ideal = { country = "DE",currency = "EUR" } +giropay = { country = "DE",currency = "EUR" } +sofort = { country = "DE",currency = "EUR" } +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,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" } +google_pay = { 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" } +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" } + + [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" } @@ -398,8 +426,8 @@ ideal = { country = "NL", currency = "EUR" } sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } [pm_filters.globepay] -ali_pay.currency = "GBP,CNY" -we_chat_pay.currency = "GBP,CNY" +ali_pay = { country = "GB",currency = "GBP,CNY" } +we_chat_pay = { country = "GB",currency = "GBP,CNY" } [pm_filters.jpmorgan] debit = { country = "CA, GB, US, AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IE, IT, LV, LT, LU, MT, NL, PL, PT, RO, SK, SI, ES, SE", currency = "USD, EUR, GBP, AUD, NZD, SGD, CAD, JPY, HKD, KRW, TWD, MXN, BRL, DKK, NOK, ZAR, SEK, CHF, CZK, PLN, TRY, AFN, ALL, DZD, AOA, ARS, AMD, AWG, AZN, BSD, BDT, BBD, BYN, BZD, BMD, BOB, BAM, BWP, BND, BGN, BIF, BTN, XOF, XAF, XPF, KHR, CVE, KYD, CLP, CNY, COP, KMF, CDF, CRC, HRK, DJF, DOP, XCD, EGP, ETB, FKP, FJD, GMD, GEL, GHS, GIP, GTQ, GYD, HTG, HNL, HUF, ISK, INR, IDR, ILS, JMD, KZT, KES, LAK, LBP, LSL, LRD, MOP, MKD, MGA, MWK, MYR, MVR, MRU, MUR, MDL, MNT, MAD, MZN, MMK, NAD, NPR, ANG, PGK, NIO, NGN, PKR, PAB, PYG, PEN, PHP, QAR, RON, RWF, SHP, WST, STN, SAR, RSD, SCR, SLL, SBD, SOS, LKR, SRD, SZL, TJS, TZS, THB, TOP, TTD, UGX, UAH, AED, UYU, UZS, VUV, VND, YER, ZMW" } @@ -427,7 +455,7 @@ credit = { country = "AE, AF, AL, AM, CW, AO, AR, AU, AW, AZ, BA, BB, BG, BH, BI google_pay = { country = "AE, AF, AL, AM, CW, AO, AR, AU, AW, AZ, BA, BB, BG, BH, BI, BM, BN, BO, BR, BS, BW, BY, BZ, CA, CD, LI, CL, CN, CO, CR, CV, CZ, DJ, DK, DO, DZ, EG, ET, AD, FJ, FK, GG, GE, GH, GI, GM, GN, GT, GY, HK, HN, HR, HT, HU, ID, IL, IQ, IS, JM, JO, JP, KG, KH, KM, KR, KW, KY, KZ, LA, LB, LR, LS, MA, MD, MG, MK, MN, MO, MR, MV, MW, MX, MY, MZ, NA, NG, NI, BV, CK, OM, PA, PE, PG, PL, PY, QA, RO, RS, RW, SA, SB, SC, SE, SG, SH, SO, SR, SV, SZ, TH, TJ, TM, TN, TO, TR, TT, TW, TZ, UG, AS, UY, UZ, VE, VN, VU, WS, CM, AI, BJ, PF, YE, ZA, ZM, ZW", currency = "AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BWP, BYN, BZD, CAD, CDF, CHF, CLP, CNY, COP, CRC, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, IQD, ISK, JMD, JOD, JPY, KGS, KHR, KMF, KRW, KWD, KYD, KZT, LAK, LBP, LRD, LSL, MAD, MDL, MGA, MKD, MNT, MOP, MRU, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NZD, OMR, PAB, PEN, PGK, PLN, PYG, QAR, RON, RSD, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SOS, SRD, SVC, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL" } [pm_filters.prophetpay] -card_redirect.currency = "USD" +card_redirect = { country = "US", currency = "USD" } [pm_filters.stax] ach = { country = "US", currency = "USD" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 8c9569d4dfb..9abe5946cfb 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -399,9 +399,37 @@ giropay = { country = "DE", currency = "EUR" } ideal = { country = "NL", currency = "EUR" } sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } +[pm_filters.itaubank] +pix = { country = "BR", currency = "BRL" } + +[pm_filters.nexinets] +credit = { country = "DE",currency = "EUR" } +debit = { country = "DE",currency = "EUR" } +ideal = { country = "DE",currency = "EUR" } +giropay = { country = "DE",currency = "EUR" } +sofort = { country = "DE",currency = "EUR" } +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,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" } +google_pay = { 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" } +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" } + + [pm_filters.globepay] -ali_pay.currency = "GBP,CNY" -we_chat_pay.currency = "GBP,CNY" +ali_pay = { country = "GB",currency = "GBP,CNY" } +we_chat_pay = { country = "GB",currency = "CNY" } [pm_filters.jpmorgan] debit = { country = "CA, GB, US, AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IE, IT, LV, LT, LU, MT, NL, PL, PT, RO, SK, SI, ES, SE", currency = "USD, EUR, GBP, AUD, NZD, SGD, CAD, JPY, HKD, KRW, TWD, MXN, BRL, DKK, NOK, ZAR, SEK, CHF, CZK, PLN, TRY, AFN, ALL, DZD, AOA, ARS, AMD, AWG, AZN, BSD, BDT, BBD, BYN, BZD, BMD, BOB, BAM, BWP, BND, BGN, BIF, BTN, XOF, XAF, XPF, KHR, CVE, KYD, CLP, CNY, COP, KMF, CDF, CRC, HRK, DJF, DOP, XCD, EGP, ETB, FKP, FJD, GMD, GEL, GHS, GIP, GTQ, GYD, HTG, HNL, HUF, ISK, INR, IDR, ILS, JMD, KZT, KES, LAK, LBP, LSL, LRD, MOP, MKD, MGA, MWK, MYR, MVR, MRU, MUR, MDL, MNT, MAD, MZN, MMK, NAD, NPR, ANG, PGK, NIO, NGN, PKR, PAB, PYG, PEN, PHP, QAR, RON, RWF, SHP, WST, STN, SAR, RSD, SCR, SLL, SBD, SOS, LKR, SRD, SZL, TJS, TZS, THB, TOP, TTD, UGX, UAH, AED, UYU, UZS, VUV, VND, YER, ZMW" } @@ -429,7 +457,7 @@ credit = { country = "AE, AF, AL, AM, CW, AO, AR, AU, AW, AZ, BA, BB, BG, BH, BI google_pay = { country = "AE, AF, AL, AM, CW, AO, AR, AU, AW, AZ, BA, BB, BG, BH, BI, BM, BN, BO, BR, BS, BW, BY, BZ, CA, CD, LI, CL, CN, CO, CR, CV, CZ, DJ, DK, DO, DZ, EG, ET, AD, FJ, FK, GG, GE, GH, GI, GM, GN, GT, GY, HK, HN, HR, HT, HU, ID, IL, IQ, IS, JM, JO, JP, KG, KH, KM, KR, KW, KY, KZ, LA, LB, LR, LS, MA, MD, MG, MK, MN, MO, MR, MV, MW, MX, MY, MZ, NA, NG, NI, BV, CK, OM, PA, PE, PG, PL, PY, QA, RO, RS, RW, SA, SB, SC, SE, SG, SH, SO, SR, SV, SZ, TH, TJ, TM, TN, TO, TR, TT, TW, TZ, UG, AS, UY, UZ, VE, VN, VU, WS, CM, AI, BJ, PF, YE, ZA, ZM, ZW", currency = "AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BWP, BYN, BZD, CAD, CDF, CHF, CLP, CNY, COP, CRC, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, IQD, ISK, JMD, JOD, JPY, KGS, KHR, KMF, KRW, KWD, KYD, KZT, LAK, LBP, LRD, LSL, MAD, MDL, MGA, MKD, MNT, MOP, MRU, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NZD, OMR, PAB, PEN, PGK, PLN, PYG, QAR, RON, RSD, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SOS, SRD, SVC, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VES, VND, VUV, WST, XAF, XCD, XOF, XPF, YER, ZAR, ZMW, ZWL" } [pm_filters.prophetpay] -card_redirect.currency = "USD" +card_redirect = { country = "US", currency = "USD" } [pm_filters.stax] ach = { country = "US", currency = "USD" } diff --git a/config/development.toml b/config/development.toml index 951cb44bd63..0ae992b39aa 100644 --- a/config/development.toml +++ b/config/development.toml @@ -574,6 +574,40 @@ google_pay = { currency = "USD,GBP,EUR,PLN" } samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } + +[pm_filters.globepay] +ali_pay = { country = "GB",currency = "GBP,CNY" } +we_chat_pay = { country = "GB",currency = "GBP,CNY" } + + +[pm_filters.itaubank] +pix = { country = "BR", currency = "BRL" } + +[pm_filters.nexinets] +credit = { country = "DE",currency = "EUR" } +debit = { country = "DE",currency = "EUR" } +ideal = { country = "DE",currency = "EUR" } +giropay = { country = "DE",currency = "EUR" } +sofort = { country = "DE",currency = "EUR" } +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,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" } +google_pay = { 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" } +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" } + + [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" } @@ -683,7 +717,7 @@ debit = { currency = "USD" } ach = { currency = "USD" } [pm_filters.prophetpay] -card_redirect = { currency = "USD" } +card_redirect = { country = "US", currency = "USD" } [pm_filters.trustpay] credit = { not_available_flows = { capture_method = "manual" } } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 55cf5166b95..ac140e446cd 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -533,7 +533,7 @@ local_bank_transfer = { country = "CN", currency = "CNY" } cashapp = { country = "US", currency = "USD" } [pm_filters.prophetpay] -card_redirect = { currency = "USD" } +card_redirect = { country = "US", currency = "USD" } [pm_filters.bankofamerica] credit = { currency = "USD" } @@ -550,6 +550,39 @@ google_pay = { currency = "USD,GBP,EUR,PLN" } samsung_pay = { currency = "USD,GBP,EUR" } paze = { currency = "USD" } +[pm_filters.globepay] +ali_pay = { country = "GB",currency = "GBP,CNY" } +we_chat_pay = { country = "GB",currency = "GBP,CNY" } + + +[pm_filters.itaubank] +pix = { country = "BR", currency = "BRL" } + +[pm_filters.nexinets] +credit = { country = "DE",currency = "EUR" } +debit = { country = "DE",currency = "EUR" } +ideal = { country = "DE",currency = "EUR" } +giropay = { country = "DE",currency = "EUR" } +sofort = { country = "DE",currency = "EUR" } +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,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" } +google_pay = { 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" } +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" } + + [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/crates/hyperswitch_connectors/src/connectors/globalpay.rs b/crates/hyperswitch_connectors/src/connectors/globalpay.rs index 72e78a7dda1..7e9ad1aa820 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay.rs @@ -1,6 +1,7 @@ mod requests; mod response; pub mod transformers; +use std::sync::LazyLock; use api_models::webhooks::IncomingWebhookEvent; use common_enums::{enums, CallConnectorAction, PaymentAction}; @@ -26,7 +27,10 @@ use hyperswitch_domain_models::{ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, SyncRequestType, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData, @@ -60,8 +64,8 @@ use crate::{ constants::headers, types::{RefreshTokenRouterData, ResponseRouterData}, utils::{ - construct_not_supported_error_report, convert_amount, get_header_key_value, - is_mandate_supported, ForeignTryFrom, PaymentMethodDataType, RefundsRequestData, + convert_amount, get_header_key_value, is_mandate_supported, ForeignTryFrom, + PaymentMethodDataType, RefundsRequestData, }, }; @@ -156,22 +160,6 @@ impl ConnectorCommon for Globalpay { } impl ConnectorValidation for Globalpay { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual - | enums::CaptureMethod::SequentialAutomatic => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - construct_not_supported_error_report(capture_method, self.id()), - ), - } - } fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, @@ -1034,4 +1022,150 @@ impl ConnectorRedirectResponse for Globalpay { } } -impl ConnectorSpecifications for Globalpay {} +static GLOBALPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + ]; + + let mut globalpay_supported_payment_methods = SupportedPaymentMethods::new(); + + globalpay_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + globalpay_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + globalpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Ideal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + globalpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Giropay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + globalpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Sofort, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + globalpay_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Eps, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + globalpay_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + globalpay_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::Paypal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + globalpay_supported_payment_methods + }); + +static GLOBALPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Globalpay", + description: "Global Payments is an American multinational financial technology company that provides payment technology and services to merchants, issuers and consumers.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + +static GLOBALPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; + +impl ConnectorSpecifications for Globalpay { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&GLOBALPAY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*GLOBALPAY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&GLOBALPAY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/globepay.rs b/crates/hyperswitch_connectors/src/connectors/globepay.rs index 0abff2a2523..0f7d4d02363 100644 --- a/crates/hyperswitch_connectors/src/connectors/globepay.rs +++ b/crates/hyperswitch_connectors/src/connectors/globepay.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; +use common_enums::enums; use common_utils::{ crypto::{self, GenerateDigest}, errors::CustomResult, @@ -21,7 +23,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -203,8 +208,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData let query_params = get_globlepay_query_params(&req.connector_auth_type)?; if matches!( req.request.capture_method, - Some(common_enums::enums::CaptureMethod::Automatic) - | Some(common_enums::enums::CaptureMethod::SequentialAutomatic) + Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic) ) { Ok(format!( "{}api/v1.0/gateway/partners/{}/orders/{}{query_params}", @@ -560,4 +564,58 @@ impl webhooks::IncomingWebhook for Globepay { } } -impl ConnectorSpecifications for Globepay {} +static GLOBEPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut globepay_supported_payment_methods = SupportedPaymentMethods::new(); + + globepay_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::AliPay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + globepay_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::WeChatPay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + globepay_supported_payment_methods + }); + +static GLOBEPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Globepay", + description: "GlobePay Limited is a professional cross-border payment solution provider (WeChat Pay & Alipay) in the UK", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + +static GLOBEPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Globepay { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&GLOBEPAY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*GLOBEPAY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&GLOBEPAY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/itaubank.rs b/crates/hyperswitch_connectors/src/connectors/itaubank.rs index 5e0914ab71a..9c5ab5b3007 100644 --- a/crates/hyperswitch_connectors/src/connectors/itaubank.rs +++ b/crates/hyperswitch_connectors/src/connectors/itaubank.rs @@ -1,8 +1,8 @@ pub mod transformers; - -use std::fmt::Write; +use std::{fmt::Write, sync::LazyLock}; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; +use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, @@ -22,7 +22,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, @@ -792,4 +795,42 @@ impl IncomingWebhook for Itaubank { } } -impl ConnectorSpecifications for Itaubank {} +static ITAUBANK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let mut itaubank_supported_payment_methods = SupportedPaymentMethods::new(); + + itaubank_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::Pix, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: Vec::new(), + specific_features: None, + }, + ); + + itaubank_supported_payment_methods + }); + +static ITAUBANK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Itaubank", + description: "Itau Bank is a leading Brazilian financial institution offering a wide range of banking services, including retail banking, loans, and investment solutions.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + +static ITAUBANK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Itaubank { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&ITAUBANK_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*ITAUBANK_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&ITAUBANK_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets.rs b/crates/hyperswitch_connectors/src/connectors/nexinets.rs index 2dd27cd768a..de6f6f5cd3c 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexinets.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexinets.rs @@ -1,4 +1,5 @@ pub mod transformers; +use std::sync::LazyLock; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_enums::enums; @@ -23,7 +24,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -52,8 +56,7 @@ use crate::{ constants::headers, types::ResponseRouterData, utils::{ - construct_not_implemented_error_report, is_mandate_supported, to_connector_meta, - PaymentMethodDataType, PaymentsSyncRequestData, + is_mandate_supported, to_connector_meta, PaymentMethodDataType, PaymentsSyncRequestData, }, }; @@ -174,23 +177,6 @@ impl ConnectorCommon for Nexinets { } impl ConnectorValidation for Nexinets { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual - | enums::CaptureMethod::SequentialAutomatic => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - construct_not_implemented_error_report(capture_method, self.id()), - ), - } - } - fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, @@ -750,7 +736,151 @@ impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, Pay // Not Implemented (R) } -impl ConnectorSpecifications for Nexinets {} +static NEXINETS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + ]; + + let mut nexinets_supported_payment_methods = SupportedPaymentMethods::new(); + + nexinets_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + nexinets_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + nexinets_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Ideal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + nexinets_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Giropay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + nexinets_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Sofort, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + nexinets_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Eps, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + nexinets_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, + }, + ); + nexinets_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::Paypal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + nexinets_supported_payment_methods + }); + +static NEXINETS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Nexinets", + description: "Nexi and Nets join forces to create The European PayTech leader, a strategic combination to offer future-proof innovative payment solutions.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + +static NEXINETS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Nexinets { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&NEXINETS_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*NEXINETS_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&NEXINETS_SUPPORTED_WEBHOOK_FLOWS) + } +} impl ConnectorTransactionId for Nexinets { #[cfg(feature = "v1")] diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei.rs b/crates/hyperswitch_connectors/src/connectors/nuvei.rs index 803a92b7c12..c6df1c01069 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei.rs @@ -1,6 +1,5 @@ pub mod transformers; - -use std::fmt::Debug; +use std::{fmt::Debug, sync::LazyLock}; use api_models::{payments::PaymentIdType, webhooks::IncomingWebhookEvent}; use common_enums::{enums, CallConnectorAction, PaymentAction}; @@ -27,7 +26,10 @@ use hyperswitch_domain_models::{ PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsAuthorizeSessionTokenRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, @@ -96,23 +98,6 @@ impl ConnectorCommon for Nuvei { } impl ConnectorValidation for Nuvei { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual - | enums::CaptureMethod::SequentialAutomatic => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - utils::construct_not_supported_error_report(capture_method, self.id()), - ), - } - } - fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, @@ -960,4 +945,175 @@ impl ConnectorRedirectResponse for Nuvei { } } -impl ConnectorSpecifications for Nuvei {} +static NUVEI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::UnionPay, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::CartesBancaires, + ]; + + let mut nuvei_supported_payment_methods = SupportedPaymentMethods::new(); + + nuvei_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + nuvei_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::Supported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + nuvei_supported_payment_methods.add( + enums::PaymentMethod::PayLater, + enums::PaymentMethodType::Klarna, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + nuvei_supported_payment_methods.add( + enums::PaymentMethod::PayLater, + enums::PaymentMethodType::AfterpayClearpay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + nuvei_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Ideal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + nuvei_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Giropay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + nuvei_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Sofort, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + nuvei_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Eps, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + nuvei_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, + }, + ); + nuvei_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + nuvei_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::Paypal, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + nuvei_supported_payment_methods +}); + +static NUVEI_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Nuvei", + description: "Nuvei is the Canadian fintech company accelerating the business of clients around the world.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + +static NUVEI_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; + +impl ConnectorSpecifications for Nuvei { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&NUVEI_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*NUVEI_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&NUVEI_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/prophetpay.rs b/crates/hyperswitch_connectors/src/connectors/prophetpay.rs index d6457e5356e..23c634b7e41 100644 --- a/crates/hyperswitch_connectors/src/connectors/prophetpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/prophetpay.rs @@ -1,9 +1,9 @@ pub mod transformers; - -use std::fmt::Debug; +use std::{fmt::Debug, sync::LazyLock}; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use base64::Engine; +use common_enums::enums; use common_utils::{ consts::BASE64_ENGINE, errors::CustomResult, @@ -24,7 +24,10 @@ use hyperswitch_domain_models::{ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -716,5 +719,47 @@ impl IncomingWebhook for Prophetpay { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } +static PROPHETPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut prophetpay_supported_payment_methods = SupportedPaymentMethods::new(); + + prophetpay_supported_payment_methods.add( + enums::PaymentMethod::CardRedirect, + enums::PaymentMethodType::CardRedirect, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + prophetpay_supported_payment_methods + }); + +static PROPHETPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Prophetpay", + description: "GlobePay Limited is a professional cross-border payment solution provider (WeChat Pay & Alipay) in the UK", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + +static PROPHETPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; -impl ConnectorSpecifications for Prophetpay {} +impl ConnectorSpecifications for Prophetpay { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&PROPHETPAY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*PROPHETPAY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&PROPHETPAY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/zen.rs b/crates/hyperswitch_connectors/src/connectors/zen.rs index ff5c13b0d2f..acb626b8bfa 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen.rs @@ -1,9 +1,8 @@ pub mod transformers; - -use std::fmt::Debug; +use std::{fmt::Debug, sync::LazyLock}; use api_models::webhooks::IncomingWebhookEvent; -use common_enums::{CallConnectorAction, PaymentAction}; +use common_enums::{enums, CallConnectorAction, PaymentAction}; use common_utils::{ crypto, errors::CustomResult, @@ -25,7 +24,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -158,7 +160,7 @@ impl ConnectorValidation for Zen { &self, _data: &PaymentsSyncData, _is_three_ds: bool, - _status: common_enums::enums::AttemptStatus, + _status: enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { // since we can make psync call with our reference_id, having connector_transaction_id is not an mandatory criteria @@ -699,4 +701,186 @@ impl ConnectorRedirectResponse for Zen { } } -impl ConnectorSpecifications for Zen {} +static ZEN_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + ]; + + let mut zen_supported_payment_methods = SupportedPaymentMethods::new(); + + zen_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(), + } + }), + ), + }, + ); + zen_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(), + } + }), + ), + }, + ); + zen_supported_payment_methods.add( + enums::PaymentMethod::Voucher, + enums::PaymentMethodType::Boleto, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + zen_supported_payment_methods.add( + enums::PaymentMethod::Voucher, + enums::PaymentMethodType::Efecty, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + zen_supported_payment_methods.add( + enums::PaymentMethod::Voucher, + enums::PaymentMethodType::PagoEfectivo, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + zen_supported_payment_methods.add( + enums::PaymentMethod::Voucher, + enums::PaymentMethodType::RedCompra, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + zen_supported_payment_methods.add( + enums::PaymentMethod::Voucher, + enums::PaymentMethodType::RedPagos, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + zen_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::Multibanco, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + zen_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::Pix, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + zen_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::Pse, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + zen_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, + }, + ); + zen_supported_payment_methods.add( + enums::PaymentMethod::Wallet, + enums::PaymentMethodType::GooglePay, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: None, + }, + ); + + zen_supported_payment_methods +}); + +static ZEN_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Zen", + description: "Zen Payment Gateway is a secure and scalable payment solution that enables businesses to accept online payments globally with various methods and currencies.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + +static ZEN_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] = + [enums::EventClass::Payments, enums::EventClass::Refunds]; + +impl ConnectorSpecifications for Zen { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&ZEN_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*ZEN_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&ZEN_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index ea6d79f3209..cbed83650de 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -299,6 +299,41 @@ przelewy24 = { country = "PL", currency = "PLN,EUR" } [pm_filters.mifinity] mifinity = { country = "BR,CN,SG,MY,DE,CH,DK,GB,ES,AD,GI,FI,FR,GR,HR,IT,JP,MX,AR,CO,CL,PE,VE,UY,PY,BO,EC,GT,HN,SV,NI,CR,PA,DO,CU,PR,NL,NO,PL,PT,SE,RU,TR,TW,HK,MO,AX,AL,DZ,AS,AO,AI,AG,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BE,BZ,BJ,BM,BT,BQ,BA,BW,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CX,CC,KM,CG,CK,CI,CW,CY,CZ,DJ,DM,EG,GQ,ER,EE,ET,FK,FO,FJ,GF,PF,TF,GA,GM,GE,GH,GL,GD,GP,GU,GG,GN,GW,GY,HT,HM,VA,IS,IN,ID,IE,IM,IL,JE,JO,KZ,KE,KI,KW,KG,LA,LV,LB,LS,LI,LT,LU,MK,MG,MW,MV,ML,MT,MH,MQ,MR,MU,YT,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NC,NZ,NE,NG,NU,NF,MP,OM,PK,PW,PS,PG,PH,PN,QA,RE,RO,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SX,SK,SI,SB,SO,ZA,GS,KR,LK,SR,SJ,SZ,TH,TL,TG,TK,TO,TT,TN,TM,TC,TV,UG,UA,AE,UZ,VU,VN,VG,VI,WF,EH,ZM", currency = "AUD,CAD,CHF,CNY,CZK,DKK,EUR,GBP,INR,JPY,NOK,NZD,PLN,RUB,SEK,ZAR,USD,EGP,UYU,UZS" } +[pm_filters.globepay] +ali_pay = { country = "GB",currency = "GBP,CNY" } +we_chat_pay = { country = "GB",currency = "GBP,CNY" } + + +[pm_filters.itaubank] +pix = { country = "BR", currency = "BRL" } + +[pm_filters.nexinets] +credit = { country = "DE",currency = "EUR" } +debit = { country = "DE",currency = "EUR" } +ideal = { country = "DE",currency = "EUR" } +giropay = { country = "DE",currency = "EUR" } +sofort = { country = "DE",currency = "EUR" } +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,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" } +google_pay = { 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" } +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" } + +[pm_filters.prophetpay] +card_redirect = { country = "US", currency = "USD" } + [pm_filters.volt] open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL" }
2025-02-12T19:58:25Z
## 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 globalpay, globepay, itaubank, nexinets, nuvei, prophetpay, zen connectors in feature matrix ### 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/feature_matrix' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jQNBYCfN5R0473yldj23Yl7HsGbCctexthWkELSAMAGpjCxKAspb2fcQDP1KmMJz' ``` Response ``` { "connector_count": 39, "connectors": [ { "name": "GLOBALPAY", "display_name": "Globalpay", "description": "Global Payments is an American multinational financial technology company that provides payment technology and services to merchants, issuers and consumers.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "DinersClub", "Discover", "Interac", "JCB", "CartesBancaires", "UnionPay" ], "supported_countries": [ "SPM", "BGD", "SEN", "GAB", "MAF", "LKA", "JPN", "TLS", "IDN", "SDN", "BEL", "TCA", "CHL", "PHL", "ERI", "GIB", "MNE", "NGA", "HRV", "NER", "NIU", "BFA", "MCO", "MEX", "SYC", "AGO", "ATG", "IRQ", "CUW", "SWZ", "CYM", "AUT", "WSM", "AND", "COG", "UKR", "CXR", "ATF", "PRI", "GNQ", "KOR", "VEN", "VCT", "REU", "SHN", "UGA", "COM", "CUB", "SUR", "VGB", "JAM", "UMI", "CHN", "EGY", "ZWE", "TUV", "SJM", "SVK", "ZMB", "BRA", "SMR", "ZAF", "GNB", "MRT", "URY", "NAM", "GLP", "IRL", "CMR", "BRN", "FIN", "HND", "ETH", "ABW", "FSM", "SVN", "SLB", "MNG", "GTM", "PRT", "SGP", "COD", "ARE", "PAN", "BES", "GUF", "KGZ", "CPV", "CHE", "MKD", "ATA", "BDI", "DOM", "TCD", "TZA", "MMR", "GGY", "MYT", "CCK", "SGS", "LUX", "VNM", "NOR", "RUS", "BLM", "MLT", "BRB", "FRA", "MUS", "NFK", "YEM", "OMN", "MDA", "MDG", "ISR", "ARM", "HMD", "BLZ", "PLW", "COK", "IND", "COL", "FLK", "BMU", "BTN", "DJI", "VAT", "TKM", "TON", "KHM", "POL", "VIR", "RWA", "HUN", "KNA", "NIC", "TUR", "LBY", "ALB", "MWI", "DZA", "BWA", "SLV", "PSE", "TUN", "SAU", "MTQ", "GUM", "LSO", "LIE", "GRC", "UZB", "CIV", "GRD", "THA", "BVT", "KWT", "AFG", "CRI", "BLR", "DMA", "KIR", "BIH", "LAO", "WLF", "SXM", "GMB", "TGO", "DNK", "CYP", "HTI", "TJK", "PRY", "MSR", "USA", "PNG", "LBN", "CAF", "QAT", "NZL", "AUS", "SYR", "SWE", "LBR", "PYF", "GHA", "DEU", "PAK", "GIN", "MAC", "TKL", "TWN", "IMN", "KEN", "SRB", "JOR", "BHS", "CZE", "MLI", "LVA", "PRK", "IOT", "ALA", "GRL", "STP", "FRO", "BGR", "SSD", "PCN", "HKG", "MHL", "GEO", "NRU", "GBR", "LTU", "ASM", "JEY", "LCA", "ECU", "AIA", "ARG", "BOL", "MYS", "BHR", "SOM", "FJI", "AZE", "ESH", "NCL", "MOZ", "CAN", "KAZ", "ITA", "BEN", "ROU", "MAR", "EST", "MDV", "VUT", "MNP", "PER", "IRN", "ESP", "NPL", "NLD", "TTO", "SLE", "ISL", "GUY" ], "supported_currencies": [ "ETB", "TWD", "KPW", "BOB", "KZT", "GTQ", "SYP", "MNT", "GBP", "MVR", "YER", "RUB", "GHS", "LYD", "QAR", "GNF", "PGK", "USD", "CLF", "BWP", "COP", "XCD", "PLN", "AOA", "SOS", "UZS", "BDT", "SSP", "MOP", "HKD", "SLL", "SCR", "ZMW", "CDF", "SAR", "AFN", "RSD", "FJD", "BIF", "SGD", "CAD", "JPY", "GEL", "FKP", "UYU", "KHR", "ZAR", "BHD", "IRR", "DOP", "MMK", "NOK", "ILS", "SRD", "TTD", "BRL", "GYD", "EUR", "MWK", "ZWL", "TND", "BND", "NIO", "MKD", "LAK", "LRD", "NAD", "EGP", "ERN", "SDG", "BMD", "HTG", "PHP", "ARS", "VUV", "CUP", "NGN", "KMF", "PEN", "MGA", "INR", "JMD", "GMD", "JOD", "BTN", "CLP", "UGX", "BGN", "ANG", "IQD", "LSL", "BZD", "BYN", "SZL", "PAB", "MXN", "LBP", "ALL", "PYG", "KES", "SEK", "CNY", "GIP", "TJS", "DZD", "TMT", "SVC", "HRK", "RWF", "CVE", "STD", "KWD", "TRY", "IDR", "HNL", "MAD", "NPR", "AWG", "CHF", "SHP", "AUD", "TOP", "WST", "KRW", "AZN", "CRC", "DJF", "MDL", "MZN", "RON", "TZS", "PKR", "CUC", "KGS", "DKK", "AMD", "ISK", "MYR", "BSD", "AED", "NZD", "THB", "MUR", "HUF", "UAH", "BBD", "CZK", "LKR", "OMR", "VND", "SBD" ] }, { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "DinersClub", "Discover", "Interac", "JCB", "CartesBancaires", "UnionPay" ], "supported_countries": [ "TCD", "JEY", "BIH", "PAN", "EST", "STP", "USA", "BTN", "KOR", "HND", "MDA", "FRO", "GHA", "SYC", "RWA", "LBN", "GRL", "BFA", "ZAF", "TLS", "WLF", "AUT", "ZWE", "BLR", "HMD", "JPN", "ATF", "COG", "GUM", "TZA", "CYP", "TKL", "UZB", "MYS", "PER", "CUB", "AIA", "SLE", "BES", "HRV", "KEN", "GRC", "NOR", "FIN", "MWI", "TUR", "GMB", "PNG", "VIR", "IOT", "CYM", "NLD", "DEU", "ETH", "SGP", "KGZ", "LAO", "ESH", "LBY", "BVT", "BGD", "IMN", "CAN", "DOM", "BOL", "MUS", "SLB", "SWZ", "CHE", "VCT", "MDG", "BEN", "ATG", "MTQ", "ABW", "SJM", "TON", "RUS", "BGR", "TUN", "BRA", "URY", "AZE", "SWE", "GGY", "SSD", "JOR", "OMN", "BRB", "PAK", "VAT", "MNE", "POL", "EGY", "NZL", "THA", "BMU", "IRQ", "UKR", "SLV", "MKD", "IDN", "PYF", "MNP", "LBR", "FSM", "COM", "BRN", "PCN", "ERI", "ITA", "FLK", "CIV", "CRI", "ISL", "MOZ", "KNA", "ECU", "PRT", "SEN", "MRT", "MEX", "CMR", "LVA", "MCO", "CHN", "ESP", "WSM", "NER", "GIN", "SUR", "ROU", "ATA", "HUN", "QAT", "NAM", "IRN", "SAU", "CCK", "GTM", "BDI", "NPL", "ASM", "CZE", "CPV", "CAF", "LSO", "LCA", "REU", "GBR", "DMA", "GNQ", "LUX", "ISR", "BWA", "PSE", "MLT", "GLP", "DZA", "UGA", "MDV", "ARE", "IRL", "GIB", "BLM", "GNB", "CXR", "JAM", "BEL", "CHL", "NCL", "VGB", "DNK", "KAZ", "BHR", "PRK", "AUS", "TWN", "IND", "LTU", "SGS", "TJK", "GEO", "NIU", "HKG", "SYR", "AGO", "COL", "SDN", "SPM", "ALB", "COD", "MLI", "TGO", "TUV", "SVN", "COK", "PRY", "CUW", "MAC", "VEN", "SOM", "GRD", "VNM", "MMR", "TKM", "KHM", "BLZ", "GAB", "HTI", "VUT", "KWT", "MNG", "MYT", "PLW", "SRB", "ALA", "MAR", "NRU", "GUF", "SXM", "MSR", "SHN", "UMI", "PRI", "TCA", "ARM", "AFG", "YEM", "DJI", "FJI", "LIE", "SVK", "PHL", "MHL", "GUY", "TTO", "AND", "FRA", "ZMB", "KIR", "ARG", "NIC", "BHS", "LKA", "NFK", "NGA", "MAF", "SMR" ], "supported_currencies": [ "PHP", "TTD", "LKR", "DOP", "CZK", "LBP", "MDL", "EUR", "SVC", "LRD", "KPW", "CHF", "QAR", "PLN", "VND", "YER", "AUD", "GYD", "SAR", "SRD", "RON", "PYG", "AED", "LYD", "PKR", "SLL", "UYU", "PAB", "SSP", "SDG", "MXN", "USD", "MGA", "MUR", "NPR", "FJD", "CNY", "PGK", "TND", "DZD", "NIO", "CVE", "MMK", "HNL", "SHP", "BRL", "ERN", "RWF", "TMT", "KES", "MYR", "INR", "IRR", "MOP", "SBD", "ZMW", "GBP", "TRY", "VUV", "HRK", "CUC", "KRW", "AWG", "IDR", "MWK", "BSD", "GHS", "BMD", "AOA", "CRC", "BWP", "MKD", "TWD", "BIF", "TJS", "ANG", "OMR", "KZT", "WST", "KWD", "EGP", "XCD", "JOD", "NZD", "SGD", "NOK", "BGN", "CUP", "RSD", "UAH", "KHR", "TZS", "TOP", "ISK", "RUB", "JMD", "MAD", "BOB", "MZN", "SCR", "NGN", "NAD", "ZAR", "ARS", "LAK", "ETB", "GIP", "GTQ", "BDT", "HKD", "UZS", "COP", "ILS", "HUF", "CAD", "LSL", "PEN", "HTG", "BYN", "SYP", "ALL", "BTN", "JPY", "IQD", "GEL", "GMD", "KGS", "CLP", "CLF", "THB", "GNF", "AFN", "BBD", "AZN", "BZD", "DKK", "DJF", "BHD", "FKP", "SZL", "SEK", "KMF", "AMD", "MVR", "UGX", "CDF", "BND", "SOS", "MNT", "ZWL", "STD" ] }, { "payment_method": "bank_redirect", "payment_method_type": "giropay", "payment_method_type_display_name": "Giropay", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "DEU" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_type_display_name": "iDEAL", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "NLD" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "bank_redirect", "payment_method_type": "sofort", "payment_method_type_display_name": "Sofort", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "BEL", "ITA", "DEU", "NLD", "ESP", "AUT" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "bank_redirect", "payment_method_type": "eps", "payment_method_type_display_name": "EPS", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "AUT" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_type_display_name": "PayPal", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": null, "supported_currencies": null }, { "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_type_display_name": "Google Pay", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": null, "supported_currencies": null } ], "supported_webhook_flows": [ "payments" ] }, { "name": "GLOBEPAY", "display_name": "Globepay", "description": "GlobePay Limited is a professional cross-border payment solution provider (WeChat Pay & Alipay) in the UK", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "wallet", "payment_method_type": "ali_pay", "payment_method_type_display_name": "Alipay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "GBR" ], "supported_currencies": [ "GBP", "CNY" ] }, { "payment_method": "wallet", "payment_method_type": "we_chat_pay", "payment_method_type_display_name": "WeChat Pay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "GBR" ], "supported_currencies": [ "CNY", "GBP" ] } ], "supported_webhook_flows": [] }, { "name": "ITAUBANK", "display_name": "Itaubank", "description": "Itau Bank is a leading Brazilian financial institution offering a wide range of banking services, including retail banking, loans, and investment solutions.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_type_display_name": "Pix", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [], "supported_countries": [ "BRA" ], "supported_currencies": [ "BRL" ] } ], "supported_webhook_flows": [] }, { "name": "NEXINETS", "display_name": "Nexinets", "description": "Nexi and Nets join forces to create The European PayTech leader, a strategic combination to offer future-proof innovative payment solutions.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "DinersClub", "Discover", "Interac", "JCB", "CartesBancaires", "UnionPay" ], "supported_countries": [ "DEU" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "DinersClub", "Discover", "Interac", "JCB", "CartesBancaires", "UnionPay" ], "supported_countries": [ "DEU" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_type_display_name": "iDEAL", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "DEU" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "bank_redirect", "payment_method_type": "giropay", "payment_method_type_display_name": "Giropay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "DEU" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "bank_redirect", "payment_method_type": "sofort", "payment_method_type_display_name": "Sofort", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "DEU" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "bank_redirect", "payment_method_type": "eps", "payment_method_type_display_name": "EPS", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "DEU" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_type_display_name": "Apple Pay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "DEU" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_type_display_name": "PayPal", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "DEU" ], "supported_currencies": [ "EUR" ] } ], "supported_webhook_flows": [] }, { "name": "NUVEI", "display_name": "Nuvei", "description": "Nuvei is the Canadian fintech company accelerating the business of clients around the world.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "UnionPay", "Interac", "JCB", "DinersClub", "Discover", "CartesBancaires" ], "supported_countries": [ "THA", "NZL", "PHL", "JPN", "GBR", "USA", "AUS", "IND", "CAN", "SGP" ], "supported_currencies": [ "GBP", "JOD", "MAD", "TTD", "TWD", "USD", "YER", "EGP", "GEL", "UAH", "CAD", "PEN", "SEK", "JPY", "BAM", "CRC", "LBP", "NZD", "OMR", "RSD", "SGD", "IDR", "PYG", "UYU", "INR", "SOS", "NAD", "MZN", "MUR", "ARS", "KYD", "PHP", "PKR", "UGX", "MMK", "IQD", "UZS", "MNT", "TOP", "TND", "LKR", "AUD", "EUR", "ISK", "TRY", "XAF", "NOK", "BMD", "RUB", "KES", "KZT", "BGN", "MKD", "RON", "VND", "KWD", "AMD", "BND", "COP", "MXN", "SAR", "AED", "CHF", "ZAR", "CNY", "CZK", "HKD", "HUF", "KGS", "AZN", "BYN", "GTQ", "BDT", "MWK", "GHS", "QAR", "DKK", "CLP", "MYR", "NGN", "DOP", "DZD", "BHD", "BRL", "KRW", "MDL", "PLN", "THB" ] }, { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "three_ds": "supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "UnionPay", "Interac", "JCB", "DinersClub", "Discover", "CartesBancaires" ], "supported_countries": [ "SGP", "GBR", "CAN", "PHL", "THA", "AUS", "USA", "NZL", "JPN", "IND" ], "supported_currencies": [ "NGN", "MXN", "RUB", "CZK", "BDT", "GBP", "IDR", "INR", "NAD", "THB", "GEL", "KZT", "SEK", "SOS", "BYN", "KYD", "CNY", "BRL", "MWK", "CLP", "DZD", "RON", "EGP", "EUR", "UZS", "BAM", "TRY", "KRW", "KES", "JPY", "KWD", "CHF", "CRC", "MYR", "MZN", "COP", "MAD", "GHS", "NOK", "CAD", "NZD", "PHP", "HKD", "OMR", "PKR", "QAR", "AED", "SGD", "TOP", "PYG", "LKR", "RSD", "UAH", "MKD", "MUR", "LBP", "BMD", "TTD", "SAR", "ARS", "HUF", "IQD", "AMD", "BND", "DKK", "DOP", "BHD", "KGS", "MNT", "JOD", "PEN", "ISK", "TWD", "UGX", "USD", "UYU", "AZN", "TND", "VND", "AUD", "YER", "ZAR", "BGN", "PLN", "XAF", "GTQ", "MMK", "MDL" ] }, { "payment_method": "pay_later", "payment_method_type": "afterpay_clearpay", "payment_method_type_display_name": "Afterpay Clearpay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "NZL", "SGP", "AUS", "USA", "IND", "PHL", "CAN", "JPN", "THA", "GBR" ], "supported_currencies": [ "MWK", "TRY", "CLP", "NAD", "UYU", "AZN", "MNT", "KZT", "XAF", "BYN", "NGN", "GBP", "DKK", "GTQ", "NOK", "SGD", "CNY", "AED", "BHD", "KYD", "IQD", "MMK", "PEN", "BDT", "TOP", "PHP", "MDL", "CAD", "AMD", "USD", "MUR", "DZD", "TTD", "RSD", "COP", "SOS", "AUD", "NZD", "BND", "PLN", "EUR", "PYG", "GHS", "BGN", "DOP", "KGS", "ARS", "KWD", "MKD", "MZN", "PKR", "SEK", "KES", "JOD", "MXN", "MAD", "RUB", "ZAR", "ISK", "CHF", "HUF", "IDR", "BRL", "QAR", "CRC", "LBP", "TND", "BAM", "UZS", "UAH", "SAR", "JPY", "OMR", "MYR", "RON", "KRW", "TWD", "UGX", "THB", "VND", "BMD", "CZK", "GEL", "EGP", "LKR", "HKD", "INR", "YER" ] }, { "payment_method": "pay_later", "payment_method_type": "klarna", "payment_method_type_display_name": "Klarna", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "USA", "SGP", "THA", "GBR", "IND", "JPN", "AUS", "CAN", "NZL", "PHL" ], "supported_currencies": [ "EGP", "SEK", "CZK", "ISK", "EUR", "MMK", "PLN", "KGS", "SOS", "THB", "MKD", "TTD", "LBP", "USD", "MNT", "RUB", "UGX", "AZN", "MZN", "NOK", "UAH", "TND", "AUD", "SGD", "KYD", "RSD", "AMD", "SAR", "JOD", "BND", "BRL", "KRW", "PHP", "TWD", "MAD", "CNY", "IDR", "MXN", "XAF", "PEN", "BMD", "BDT", "KWD", "PKR", "ZAR", "YER", "DZD", "LKR", "PYG", "UZS", "GHS", "QAR", "NZD", "TRY", "UYU", "COP", "MYR", "GTQ", "NGN", "JPY", "NAD", "DOP", "BAM", "CHF", "KZT", "MDL", "BGN", "ARS", "AED", "CLP", "BYN", "BHD", "CRC", "GEL", "IQD", "CAD", "KES", "MUR", "OMR", "TOP", "GBP", "VND", "DKK", "MWK", "RON", "HUF", "HKD", "INR" ] }, { "payment_method": "bank_redirect", "payment_method_type": "eps", "payment_method_type_display_name": "EPS", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "PHL", "USA", "AUS", "CAN", "NZL", "SGP", "GBR", "JPN", "THA", "IND" ], "supported_currencies": [ "DZD", "PHP", "TTD", "AMD", "XAF", "AZN", "NGN", "TOP", "IQD", "OMR", "MDL", "BHD", "MUR", "MWK", "USD", "GEL", "COP", "CNY", "AED", "KRW", "GBP", "KZT", "NOK", "HKD", "LKR", "SEK", "EGP", "HUF", "QAR", "UGX", "INR", "MMK", "THB", "MKD", "NZD", "UZS", "CHF", "LBP", "KWD", "TND", "KES", "IDR", "PYG", "RON", "VND", "SOS", "BAM", "KYD", "ZAR", "MNT", "BDT", "DKK", "ISK", "NAD", "CZK", "CAD", "MYR", "CRC", "GTQ", "MZN", "JOD", "JPY", "BMD", "BYN", "MAD", "MXN", "PEN", "SAR", "TRY", "ARS", "CLP", "BGN", "KGS", "RSD", "RUB", "SGD", "EUR", "PLN", "GHS", "TWD", "DOP", "UAH", "YER", "UYU", "PKR", "BND", "BRL", "AUD" ] }, { "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_type_display_name": "iDEAL", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "NZL", "AUS", "CAN", "SGP", "GBR", "JPN", "THA", "USA", "IND", "PHL" ], "supported_currencies": [ "GHS", "NGN", "EUR", "DKK", "JPY", "BGN", "MUR", "MXN", "KYD", "KGS", "RUB", "EGP", "TOP", "BAM", "TRY", "KWD", "LBP", "HKD", "HUF", "LKR", "TND", "ISK", "GTQ", "MAD", "MKD", "BYN", "TTD", "OMR", "YER", "BHD", "AZN", "UAH", "PEN", "ZAR", "PHP", "KZT", "CAD", "GEL", "SGD", "VND", "USD", "XAF", "IQD", "MMK", "NZD", "PYG", "QAR", "RON", "UGX", "TWD", "ARS", "JOD", "CRC", "PKR", "MDL", "INR", "KES", "IDR", "COP", "CNY", "BND", "AED", "BDT", "CLP", "MZN", "PLN", "RSD", "CZK", "MYR", "DOP", "SAR", "CHF", "KRW", "THB", "MNT", "AMD", "BRL", "GBP", "UYU", "UZS", "AUD", "NAD", "SEK", "BMD", "DZD", "MWK", "NOK", "SOS" ] }, { "payment_method": "bank_redirect", "payment_method_type": "sofort", "payment_method_type_display_name": "Sofort", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "AUS", "NZL", "JPN", "GBR", "USA", "IND", "THA", "PHL", "CAN", "SGP" ], "supported_currencies": [ "PLN", "BAM", "MXN", "TOP", "MUR", "DOP", "BMD", "EUR", "MWK", "NOK", "PHP", "UZS", "VND", "BRL", "BDT", "AMD", "AZN", "GHS", "THB", "LKR", "BYN", "RSD", "BGN", "GTQ", "UGX", "CZK", "BHD", "EGP", "AED", "KRW", "MNT", "MKD", "NZD", "MAD", "RUB", "MMK", "LBP", "TND", "YER", "JOD", "DZD", "KZT", "HKD", "COP", "HUF", "JPY", "BND", "CRC", "ISK", "OMR", "UAH", "CAD", "IDR", "MDL", "MZN", "NAD", "PYG", "TTD", "ZAR", "MYR", "UYU", "TWD", "PKR", "SEK", "CNY", "KES", "QAR", "USD", "GBP", "GEL", "KYD", "TRY", "PEN", "AUD", "CLP", "IQD", "SOS", "CHF", "NGN", "KWD", "SAR", "INR", "RON", "SGD", "DKK", "ARS", "XAF", "KGS" ] }, { "payment_method": "bank_redirect", "payment_method_type": "giropay", "payment_method_type_display_name": "Giropay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "GBR", "THA", "PHL", "NZL", "IND", "USA", "AUS", "JPN", "SGP", "CAN" ], "supported_currencies": [ "TND", "UZS", "TRY", "DZD", "CZK", "ISK", "TTD", "GBP", "GHS", "MUR", "MWK", "KZT", "NGN", "KGS", "JPY", "PLN", "NOK", "BYN", "BND", "KWD", "PYG", "RON", "MDL", "RSD", "THB", "VND", "NAD", "HKD", "GTQ", "BAM", "XAF", "BDT", "PEN", "IDR", "LKR", "MNT", "CRC", "KES", "DOP", "PHP", "CHF", "MXN", "EGP", "SEK", "SOS", "UYU", "UAH", "LBP", "BGN", "PKR", "USD", "GEL", "AZN", "MMK", "BRL", "COP", "QAR", "ZAR", "UGX", "ARS", "CLP", "RUB", "CNY", "CAD", "SGD", "DKK", "INR", "OMR", "TWD", "KRW", "SAR", "MYR", "HUF", "TOP", "AED", "MAD", "MZN", "EUR", "BMD", "KYD", "MKD", "JOD", "NZD", "AUD", "IQD", "YER", "AMD", "BHD" ] }, { "payment_method": "wallet", "payment_method_type": "paypal", "payment_method_type_display_name": "PayPal", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "CAN", "THA", "USA", "JPN", "AUS", "PHL", "SGP", "GBR", "NZL", "IND" ], "supported_currencies": [ "BRL", "SEK", "BHD", "MDL", "MZN", "SOS", "NZD", "EUR", "KYD", "OMR", "PKR", "TWD", "AUD", "YER", "BAM", "CLP", "GBP", "UYU", "NAD", "HUF", "JOD", "MWK", "UZS", "ISK", "VND", "LKR", "USD", "MNT", "AZN", "RUB", "DOP", "UAH", "AED", "INR", "DKK", "HKD", "KWD", "BDT", "PHP", "IQD", "EGP", "MAD", "BGN", "MYR", "PLN", "THB", "BYN", "MXN", "CAD", "COP", "PYG", "AMD", "TOP", "TRY", "GEL", "NGN", "CRC", "KGS", "CHF", "MMK", "MUR", "GTQ", "QAR", "RSD", "TND", "DZD", "NOK", "RON", "SGD", "TTD", "UGX", "KZT", "CZK", "XAF", "KES", "ARS", "LBP", "GHS", "BND", "MKD", "CNY", "ZAR", "KRW", "IDR", "PEN", "SAR", "JPY", "BMD" ] }, { "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_type_display_name": "Apple Pay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "SGP", "USA", "CAN", "GBR", "PHL", "AUS", "NZL", "THA", "IND", "JPN" ], "supported_currencies": [ "UZS", "XAF", "DOP", "TRY", "ISK", "AED", "BND", "PYG", "CRC", "BGN", "OMR", "PEN", "GEL", "BAM", "CZK", "NAD", "RON", "CHF", "MWK", "BRL", "MYR", "BDT", "HUF", "JPY", "LKR", "MAD", "RSD", "RUB", "BMD", "BYN", "AMD", "KGS", "TND", "TWD", "AUD", "IDR", "KYD", "MXN", "ARS", "CLP", "MDL", "NGN", "SOS", "TOP", "TTD", "LBP", "GHS", "KWD", "MKD", "MNT", "CAD", "EUR", "ZAR", "IQD", "PKR", "PHP", "UAH", "UYU", "UGX", "USD", "BHD", "KRW", "CNY", "SEK", "PLN", "YER", "NZD", "THB", "KES", "COP", "HKD", "KZT", "GTQ", "MZN", "GBP", "JOD", "MMK", "NOK", "EGP", "DKK", "VND", "MUR", "INR", "SGD", "SAR", "DZD", "AZN", "QAR" ] }, { "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_type_display_name": "Google Pay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "SGP", "PHL", "AUS", "NZL", "USA", "CAN", "JPN", "THA", "GBR", "IND" ], "supported_currencies": [ "RON", "MAD", "TWD", "AZN", "MYR", "UAH", "CZK", "DKK", "TND", "MDL", "MNT", "NAD", "PEN", "ZAR", "KWD", "ARS", "GBP", "GEL", "RSD", "JPY", "JOD", "KYD", "USD", "SAR", "CNY", "KZT", "PLN", "UZS", "YER", "EGP", "BYN", "GTQ", "NGN", "BRL", "QAR", "AED", "DZD", "MWK", "RUB", "KRW", "SGD", "CHF", "BDT", "TTD", "BMD", "THB", "UGX", "XAF", "BGN", "MZN", "MXN", "PYG", "VND", "AMD", "LKR", "NOK", "PHP", "ISK", "CLP", "COP", "EUR", "AUD", "BAM", "TOP", "KGS", "UYU", "IQD", "NZD", "LBP", "MMK", "DOP", "IDR", "HUF", "HKD", "CRC", "GHS", "SEK", "CAD", "INR", "TRY", "MKD", "OMR", "BND", "PKR", "SOS", "MUR", "BHD", "KES" ] } ], "supported_webhook_flows": [ "payments" ] }, { "name": "PROPHETPAY", "display_name": "Prophetpay", "description": "GlobePay Limited is a professional cross-border payment solution provider (WeChat Pay & Alipay) in the UK", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card_redirect", "payment_method_type": "card_redirect", "payment_method_type_display_name": "Card Redirect", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "USA" ], "supported_currencies": [ "USD" ] } ], "supported_webhook_flows": [] }, { "name": "ZEN", "display_name": "Zen", "description": "Zen Payment Gateway is a secure and scalable payment solution that enables businesses to accept online payments globally with various methods and currencies.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_type_display_name": "Pix", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "BRA" ], "supported_currencies": [ "BRL" ] }, { "payment_method": "bank_transfer", "payment_method_type": "multibanco", "payment_method_type_display_name": "Multibanco", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "PRT" ], "supported_currencies": [ "EUR" ] }, { "payment_method": "bank_transfer", "payment_method_type": "pse", "payment_method_type_display_name": "PSE", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "COL" ], "supported_currencies": [ "COP" ] }, { "payment_method": "wallet", "payment_method_type": "google_pay", "payment_method_type_display_name": "Google Pay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": null, "supported_currencies": null }, { "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_type_display_name": "Apple Pay", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": null, "supported_currencies": null }, { "payment_method": "voucher", "payment_method_type": "efecty", "payment_method_type_display_name": "Efecty", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "COL" ], "supported_currencies": [ "COP" ] }, { "payment_method": "voucher", "payment_method_type": "red_compra", "payment_method_type_display_name": "RedCompra", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "CHL" ], "supported_currencies": [ "CLP" ] }, { "payment_method": "voucher", "payment_method_type": "pago_efectivo", "payment_method_type_display_name": "PagoEfectivo", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "PER" ], "supported_currencies": [ "PEN" ] }, { "payment_method": "voucher", "payment_method_type": "red_pagos", "payment_method_type_display_name": "RedPagos", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "URY" ], "supported_currencies": [ "UYU" ] }, { "payment_method": "voucher", "payment_method_type": "boleto", "payment_method_type_display_name": "Boleto Bancário", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "BRA" ], "supported_currencies": [ "BRL" ] }, { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "DinersClub", "Discover", "Interac", "JCB", "CartesBancaires", "UnionPay" ], "supported_countries": null, "supported_currencies": null }, { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Visa", "Mastercard", "AmericanExpress", "DinersClub", "Discover", "Interac", "JCB", "CartesBancaires", "UnionPay" ], "supported_countries": null, "supported_currencies": null } ], "supported_webhook_flows": [ "payments", "refunds" ] } ] } ``` ## 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.114.0
bc7679d54f09c04037604c04e6a655ed5bf264cd
bc7679d54f09c04037604c04e6a655ed5bf264cd
juspay/hyperswitch
juspay__hyperswitch-7800
Bug: [ENHANCEMENT] add validation for return_url for Payment Links HyperSwitch should always validate the presence of return_url during payment link creation as it is a required field in payment link flows.
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index bdf7e9ec83f..e606291b8db 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -6338,16 +6338,19 @@ pub fn get_key_params_for_surcharge_details( } pub fn validate_payment_link_request( - confirm: Option<bool>, + request: &api::PaymentsRequest, ) -> Result<(), errors::ApiErrorResponse> { - if let Some(cnf) = confirm { - if !cnf { - return Ok(()); - } else { - return Err(errors::ApiErrorResponse::InvalidRequestData { - message: "cannot confirm a payment while creating a payment link".to_string(), - }); - } + #[cfg(feature = "v1")] + if request.confirm == Some(true) { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "cannot confirm a payment while creating a payment link".to_string(), + }); + } + + if request.return_url.is_none() { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "return_url must be sent while creating a payment link".to_string(), + }); } Ok(()) } diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 801c6844f9b..f1b15be199e 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -979,7 +979,7 @@ impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentDat if let Some(payment_link) = &request.payment_link { if *payment_link { - helpers::validate_payment_link_request(request.confirm)?; + helpers::validate_payment_link_request(request)?; } };
2025-04-11T15:36:37Z
## 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 a validation for `return_url` when creating payment links. Return URL must be a required parameter as payment links is client side facing and needs to be redirected to an end URL post payment completion. ### 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 fixes a bug in the payment links flow which allowed creating payment links without validating presence of `return_url`. This allows merchants to be careful of payment link integration. ## How did you test it? <details> <summary>1. Create a payment link without return_url in the payments create request</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ddmeaxUlgRPHkcqtmZZm5nGMRhejMxXijYCnsp070Oqn2y4lrfUNBCb9UmedwgMt' \ --data-raw '{"customer_id":"cus_ttQVCva9zDC2q8jfJaiy","profile_id":"pro_510ieWUUX4pc0bUWmBW3","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":10,"currency":"EUR","payment_link":true,"capture_method":"automatic","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"HK","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"}}' Response { "error": { "type": "invalid_request", "message": "return_url must be sent while creating a payment link", "code": "IR_06" } } </details> <details> <summary>2. Create a payment link with return_url in the payments create request</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ddmeaxUlgRPHkcqtmZZm5nGMRhejMxXijYCnsp070Oqn2y4lrfUNBCb9UmedwgMt' \ --data-raw '{"customer_id":"cus_ttQVCva9zDC2q8jfJaiy","profile_id":"pro_510ieWUUX4pc0bUWmBW3","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":10,"currency":"EUR","payment_link":true,"capture_method":"automatic","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"HK","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"return_url":"https://example.com"}' Response {"payment_id":"pay_jqWIxxAzZ55ObDFPUi3u","merchant_id":"merchant_1744368926","status":"requires_payment_method","amount":10,"net_amount":10,"shipping_cost":null,"amount_capturable":10,"amount_received":null,"connector":null,"client_secret":"pay_jqWIxxAzZ55ObDFPUi3u_secret_R696m3FdANBfOlBHs7e3","created":"2025-04-11T15:32:20.593Z","currency":"EUR","customer_id":"cus_ttQVCva9zDC2q8jfJaiy","customer":{"id":"cus_ttQVCva9zDC2q8jfJaiy","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"HK","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://example.com/","authentication_type":null,"statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_ttQVCva9zDC2q8jfJaiy","created_at":1744385540,"expires":1744389140,"secret":"epk_4687716462814249b8cad4ebb30c18a3"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1744368926/pay_jqWIxxAzZ55ObDFPUi3u?locale=en","secure_link":null,"payment_link_id":"plink_2tsEloeZ8SeUXyOQfRsu"},"profile_id":"pro_510ieWUUX4pc0bUWmBW3","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-11T15:47:20.588Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-11T15:32:20.612Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} </details> ## 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.113.0
2123f63bc54030adf1d8f42f08240c71b03fc09c
2123f63bc54030adf1d8f42f08240c71b03fc09c
juspay/hyperswitch
juspay__hyperswitch-7813
Bug: [BUG(GlobalPay)] 5xx when making a failure payment ``` { "id": "TRN_OCPelRWxFohVEl0AuYglPyqG3fQ9r6_ca0584bb55bf", "time_created": "2025-04-14T14:54:57.880Z", "type": "SALE", "status": "DECLINED", "channel": "CNP", "capture_mode": "AUTO", "amount": "", "currency": "", "country": "DE", "merchant_id": "MER_c4c0df11039c48a9b63701adeaa296c3", "merchant_name": "Sandbox_merchant_2", "account_id": "TRA_6716058969854a48b33347043ff8225f", "account_name": "Transaction_Processing", "reference": "93459c78-f3f9-427c-84df-ca0584bb55bf", "payment_method": { "result": "108", "message": "Using test system. Please use pre-approved test cards ONLY", "entry_mode": "ECOM", "authentication": { "cavv_result": "" }, "card": { "brand": "VISA", "masked_number_last4": "XXXXXXXXXXXXXX0091", "authcode": "", "brand_reference": "", "brand_time_created": "", "cvv_result": "", "avs_address_result": "", "avs_postal_code_result": "", "avs_action": "", "provider": { "result": "108" } } }, "batch_id": "", "action": { "id": "ACT_OCPelRWxFohVEl0AuYglPyqG3fQ9r6", "type": "AUTHORIZE", "time_created": "2025-04-14T14:54:57.880Z", "result_code": "DECLINED", "app_id": "U1lRHKomEn7DN907RCDPxVhyMfiMLcfy", "app_name": "dev_portal_demo" } } ``` connector sends above response in case of failure (card decline). we get an empty currency. this results in deserialization failure and it is not intended.
diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs index f0f7851a419..11bd9e1a047 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs @@ -4,6 +4,7 @@ use masking::Secret; use serde::{Deserialize, Serialize}; use super::requests; +use crate::utils::deserialize_optional_currency; #[derive(Debug, Serialize, Deserialize)] pub struct GlobalpayPaymentsResponse { @@ -31,6 +32,7 @@ pub struct GlobalpayPaymentsResponse { /// The country in ISO-3166-1(alpha-2 code) format. pub country: Option<String>, /// The currency of the amount in ISO-4217(alpha-3) + #[serde(deserialize_with = "deserialize_optional_currency")] pub currency: Option<Currency>, /// Information relating to a currency conversion. pub currency_conversion: Option<requests::CurrencyConversion>, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index ef5559d5453..60cb878d9a3 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -6073,3 +6073,21 @@ pub fn normalize_string(value: String) -> Result<String, regex::Error> { let normalized = regex.replace_all(&lowercase_value, "").to_string(); Ok(normalized) } + +/// Custom deserializer for Option<Currency> that treats empty strings as None +pub fn deserialize_optional_currency<'de, D>( + deserializer: D, +) -> Result<Option<enums::Currency>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let string_data: Option<String> = Option::deserialize(deserializer)?; + match string_data { + Some(ref value) if !value.is_empty() => value + .clone() + .parse_enum("Currency") + .map(Some) + .map_err(|_| serde::de::Error::custom(format!("Invalid currency code: {}", value))), + _ => Ok(None), + } +}
2025-04-15T07:59:49Z
## 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 an edge case with GlobalPay where, upon payment decline, we get a deserialization error and that is because `currency` field is not expected to be empty but rather a valid `Currency` enum. ### 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 https://github.com/juspay/hyperswitch/issues/7813 ## 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)? --> cards: ```txt // successful cards "card_number": "4012001038488884", "card_number": "4222000006285344", "card_number": "4012001037167778", "card_number": "4222000005218627", "card_number": "4222000009719489", // failure cards "card_number": "4242420000000091", "card_number": "5100000000000131", ``` create a payment: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_5WtyfFxKHentO9ERR1HP8qrlIPzPP5s1Khs2G2q7mZBl1zJDOUFC3ZNzPcQtfynW' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242420000000091", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "101" } }, "billing": { "address": { "country": "US" } } }' ``` ```json { "payment_id": "pay_9iWUNJmnm8Le4l8iZCV9", "merchant_id": "postman_merchant_GHAction_95a905d4-93fe-42b4-b125-c1ddafa26313", "status": "failed", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "globalpay", "client_secret": "pay_9iWUNJmnm8Le4l8iZCV9_secret_RyifkSKcDrOFEEqC0OZ7", "created": "2025-04-15T09:21:39.674Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0091", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": null, "country": "US", "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": null, "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": "111", "error_message": "(111)[ test system ] Strong Customer Authentication Required", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1744708899, "expires": 1744712499, "secret": "epk_24e7b6b84ca647aaa39a01fbdf5c0f42" }, "manual_retry_allowed": true, "connector_transaction_id": "TRN_uRk00jWtySUhGnJD4e7mZhEQQwZ6vF_Le4l8iZCV9_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_I2x5oXH0EQeuMaAZSe6G", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NN71g0D5WXMeggXKXhBM", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-15T09:36:39.674Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-15T09:21:41.821Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": "111", "issuer_error_message": "(111)[ test system ] Strong Customer Authentication Required" } ``` payment now fails with valid error message when `failure` cards are used. previously, we would get a 5xx: ``` {"error":{"type":"api","message":"Something went wrong","code":"HE_00"}} ├╴at crates/router/src/services/api.rs:806:14 │ ├─▶ {"error":{"type":"server_not_available","code":"HE_00","message":"Something went wrong"}} │ ╰╴at crates/router/src/core/errors/utils.rs:281:17 │ ├─▶ Failed to deserialize connector response │ ╰╴at crates/hyperswitch_connectors/src/connectors/globalpay.rs:757:14 │ ├─▶ Failed to parse struct: Globalpay PaymentsResponse │ ├╴at /router/crates/common_utils/src/ext_traits.rs:175:14 │ ╰╴Unable to parse hyperswitch_connectors::connectors::globalpay::response::GlobalpayPaymentsResponse from bytes b"{\"id\":\"TRN_dsWF5Tk8k8m1ylUC4Fz3319DPwyUt0_mCSfvURrUj_1\",\"time_created\":\"2025-04-14T14:43:41.794Z\",\"type\":\"SALE\",\"status\":\"DECLINED\",\"channel\":\"CNP\",\"capture_mode\":\"AUTO\",\"amount\":\"\",\"currency\":\"\",\"country\":\"US\",\"merchant_id\":\"MER_7e3e2c7df34f42819b3edee31022ee3f\",\"merchant_name\":\"Sandbox_merchant_3\",\"account_id\":\"TRA_c9967ad7d8ec4b46b6dd44a61cde9a91\",\"account_name\":\"transaction_processing\",\"reference\":\"pay_gO7eiUCttdmCSfvURrUj_1\",\"payment_method\":{\"result\":\"111\",\"message\":\"(111)[ test system ] Strong Customer Authentication Required\",\"entry_mode\":\"ECOM\",\"authentication\":{\"cavv_result\":\"\"},\"card\":{\"funding\":\"CREDIT\",\"brand\":\"MASTERCARD\",\"masked_number_last4\":\"XXXXXXXXXXXX0131\",\"authcode\":\"\",\"brand_reference\":\"YWLv8HtAwSh6aG8F\",\"brand_time_created\":\"\",\"tag_response\":\"\",\"cvv_result\":\"MATCHED\",\"avs_address_result\":\"MATCHED\",\"avs_postal_code_result\":\"MATCHED\",\"avs_action\":\"\",\"provider\":{\"result\":\"111\",\"cvv_result\":\"M\",\"avs_address_result\":\"M\",\"avs_postal_code_result\":\"M\"}}},\"risk_assessment\":[{\"mode\":\"ACTIVE\",\"result\":\"ACCEPTED\",\"rules\":[{\"reference\":\"0c93a6c9-7649-4822-b5ea-1efa356337fd\",\"description\":\"Cardholder Name Rule\",\"mode\":\"ACTIVE\",\"result\":\"ACCEPTED\"},{\"reference\":\"a539d51a-abc1-4fff-a38e-b34e00ad0cc3\",\"description\":\"CardNumber block\",\"mode\":\"ACTIVE\",\"result\":\"ACCEPTED\"},{\"reference\":\"d023a19e-6985-4fda-bb9b-5d4e0dedbb1e\",\"description\":\"Amount test\",\"mode\":\"ACTIVE\",\"result\":\"ACCEPTED\"}]}],\"currency_conversion\":{\"payer_amount\":\"\",\"payer_currency\":\"\",\"exchange_rate\":\"\",\"margin_rate_percentage\":\"\",\"commission_percentage\":\"\",\"exchange_rate_source\":\"\",\"exchange_rate_time_created\":\"\"},\"batch_id\":\"\",\"action\":{\"id\":\"ACT_dsWF5Tk8k8m1ylUC4Fz3319DPwyUt0\",\"type\":\"AUTHORIZE\",\"time_created\":\"2025-04-14T14:43:41.794Z\",\"result_code\":\"DECLINED\",\"app_id\":\"OXKlGGm6ecZLIqMyRgPHRfMxdUAiEcp8\",\"app_name\":\"rotate_again\"}}" │ ╰─▶ unknown variant ``, expected one of `AED`, `AFN`, `ALL`, `AMD`, `ANG`, `AOA`, `ARS`, `AUD`, `AWG`, `AZN`, `BAM`, `BBD`, `BDT`, `BGN`, `BHD`, `BIF`, `BMD`, `BND`, `BOB`, `BRL`, `BSD`, `BTN`, `BWP`, `BYN`, `BZD`, `CAD`, `CDF`, `CHF`, `CLF`, `CLP`, `CNY`, `COP`, `CRC`, `CUC`, `CUP`, `CVE`, `CZK`, `DJF`, `DKK`, `DOP`, `DZD`, `EGP`, `ERN`, `ETB`, `EUR`, `FJD`, `FKP`, `GBP`, `GEL`, `GHS`, `GIP`, `GMD`, `GNF`, `GTQ`, `GYD`, `HKD`, `HNL`, `HRK`, `HTG`, `HUF`, `IDR`, `ILS`, `INR`, `IQD`, `IRR`, `ISK`, `JMD`, `JOD`, `JPY`, `KES`, `KGS`, `KHR`, `KMF`, `KPW`, `KRW`, `KWD`, `KYD`, `KZT`, `LAK`, `LBP`, `LKR`, `LRD`, `LSL`, `LYD`, `MAD`, `MDL`, `MGA`, `MKD`, `MMK`, `MNT`, `MOP`, `MRU`, `MUR`, `MVR`, `MWK`, `MXN`, `MYR`, `MZN`, `NAD`, `NGN`, `NIO`, `NOK`, `NPR`, `NZD`, `OMR`, `PAB`, `PEN`, `PGK`, `PHP`, `PKR`, `PLN`, `PYG`, `QAR`, `RON`, `RSD`, `RUB`, `RWF`, `SAR`, `SBD`, `SCR`, `SDG`, `SEK`, `SGD`, `SHP`, `SLE`, `SLL`, `SOS`, `SRD`, `SSP`, `STD`, `STN`, `SVC`, `SYP`, `SZL`, `THB`, `TJS`, `TMT`, `TND`, `TOP`, `TRY`, `TTD`, `TWD`, `TZS`, `UAH`, `UGX`, `USD`, `UYU`, `UZS`, `VES`, `VND`, `VUV`, `WST`, `XAF`, `XCD`, `XOF`, `XPF`, `YER`, `ZAR`, `ZMW`, `ZWL` at line 1 column 195 ╰╴at /router/crates/common_utils/src/ext_traits.rs:175:14 ``` ## 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.113.0
e8e0b5df0e2d8e5d24fb8c1e98ce5b1049cc2f66
e8e0b5df0e2d8e5d24fb8c1e98ce5b1049cc2f66
juspay/hyperswitch
juspay__hyperswitch-7809
Bug: Deep health check failing because of OpenSearch When you don't have OpenSearch deployed for Global Search feature on dashboard , the `/health/ready` ( deep health check ) API which checks health of all the underlying queryable resources fails because if OpenSearch is not present the health check fails which should not be the case.
diff --git a/config/config.example.toml b/config/config.example.toml index 5f13eb1388d..b422892afc0 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -887,6 +887,7 @@ region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. [opensearch] host = "https://localhost:9200" +enabled = false [opensearch.auth] auth = "basic" diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index b2ee7f39741..5621a4940e8 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -242,6 +242,7 @@ region = "report_download_config_region" # Region of the buc [opensearch] host = "https://localhost:9200" +enabled = false [opensearch.auth] auth = "basic" diff --git a/config/development.toml b/config/development.toml index 89e35448af2..9bf2051b1d7 100644 --- a/config/development.toml +++ b/config/development.toml @@ -968,6 +968,7 @@ keys = "accept-language,user-agent,x-profile-id" [opensearch] host = "https://localhost:9200" +enabled = false [opensearch.auth] auth = "basic" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index cdf82f60936..59b36d73fe2 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -763,6 +763,7 @@ keys = "accept-language,user-agent,x-profile-id" [opensearch] host = "https://opensearch:9200" +enabled = false [opensearch.auth] auth = "basic" diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index 726e38e5e16..20be0116d99 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -71,6 +71,8 @@ pub struct OpenSearchConfig { host: String, auth: OpenSearchAuth, indexes: OpenSearchIndexes, + #[serde(default)] + enabled: bool, } impl Default for OpenSearchConfig { @@ -91,12 +93,15 @@ impl Default for OpenSearchConfig { sessionizer_refunds: "sessionizer-refund-events".to_string(), sessionizer_disputes: "sessionizer-dispute-events".to_string(), }, + enabled: false, } } } #[derive(Debug, thiserror::Error)] pub enum OpenSearchError { + #[error("Opensearch is not enabled")] + NotEnabled, #[error("Opensearch connection error")] ConnectionError, #[error("Opensearch NON-200 response content: '{0}'")] @@ -176,6 +181,12 @@ impl ErrorSwitch<ApiErrorResponse> for OpenSearchError { "Access Forbidden error", None, )), + Self::NotEnabled => ApiErrorResponse::InternalServerError(ApiError::new( + "IR", + 8, + "Opensearch is not enabled", + None, + )), } } } @@ -408,15 +419,24 @@ impl OpenSearchAuth { } impl OpenSearchConfig { - pub async fn get_opensearch_client(&self) -> StorageResult<OpenSearchClient> { - Ok(OpenSearchClient::create(self) - .await - .map_err(|_| StorageError::InitializationError)?) + pub async fn get_opensearch_client(&self) -> StorageResult<Option<OpenSearchClient>> { + if !self.enabled { + return Ok(None); + } + Ok(Some( + OpenSearchClient::create(self) + .await + .change_context(StorageError::InitializationError)?, + )) } pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; + if !self.enabled { + return Ok(()); + } + when(self.host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch host must not be empty".into(), @@ -430,6 +450,7 @@ impl OpenSearchConfig { Ok(()) } } + #[derive(Debug, serde::Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum OpenSearchHealthStatus { diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index cc242f86a5b..ca6b870f889 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -2245,7 +2245,10 @@ pub mod routes { .collect(); analytics::search::msearch_results( - &state.opensearch_client, + state + .opensearch_client + .as_ref() + .ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?, req, search_params, SEARCH_INDEXES.to_vec(), @@ -2392,9 +2395,16 @@ pub mod routes { }) }) .collect(); - analytics::search::search_results(&state.opensearch_client, req, search_params) - .await - .map(ApplicationResponse::Json) + analytics::search::search_results( + state + .opensearch_client + .as_ref() + .ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?, + req, + search_params, + ) + .await + .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs index 2e5c2956013..c4892c94d6f 100644 --- a/crates/router/src/core/health_check.rs +++ b/crates/router/src/core/health_check.rs @@ -138,12 +138,15 @@ impl HealthCheckInterface for app::SessionState { async fn health_check_opensearch( &self, ) -> CustomResult<HealthState, errors::HealthCheckDBError> { - self.opensearch_client - .deep_health_check() - .await - .change_context(errors::HealthCheckDBError::OpensearchError)?; - - Ok(HealthState::Running) + if let Some(client) = self.opensearch_client.as_ref() { + client + .deep_health_check() + .await + .change_context(errors::HealthCheckDBError::OpensearchError)?; + Ok(HealthState::Running) + } else { + Ok(HealthState::NotApplicable) + } } async fn health_check_outgoing( diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f6386a9e2c5..4ecd093f250 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -118,7 +118,7 @@ pub struct SessionState { pub base_url: String, pub tenant: Tenant, #[cfg(feature = "olap")] - pub opensearch_client: Arc<OpenSearchClient>, + pub opensearch_client: Option<Arc<OpenSearchClient>>, pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, pub locale: String, @@ -223,7 +223,7 @@ pub struct AppState { #[cfg(feature = "olap")] pub pools: HashMap<id_type::TenantId, AnalyticsProvider>, #[cfg(feature = "olap")] - pub opensearch_client: Arc<OpenSearchClient>, + pub opensearch_client: Option<Arc<OpenSearchClient>>, pub request_id: Option<RequestId>, pub file_storage_client: Arc<dyn FileStorageInterface>, pub encryption_client: Arc<dyn EncryptionManagementInterface>, @@ -342,12 +342,12 @@ impl AppState { #[allow(clippy::expect_used)] #[cfg(feature = "olap")] - let opensearch_client = Arc::new( - conf.opensearch - .get_opensearch_client() - .await - .expect("Failed to create opensearch client"), - ); + let opensearch_client = conf + .opensearch + .get_opensearch_client() + .await + .expect("Failed to initialize OpenSearch client.") + .map(Arc::new); #[allow(clippy::expect_used)] let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable) @@ -501,7 +501,7 @@ impl AppState { #[cfg(feature = "email")] email_client: Arc::clone(&self.email_client), #[cfg(feature = "olap")] - opensearch_client: Arc::clone(&self.opensearch_client), + opensearch_client: self.opensearch_client.clone(), grpc_client: Arc::clone(&self.grpc_client), theme_storage_client: self.theme_storage_client.clone(), locale: locale.unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string()),
2025-04-14T15:46:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Making `OpenSearchClient` optional based on the config for querying OpenSearch Server for dashboard based on the Deployment status of the same ( OpenSearch Server ). ### 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). --> When you don't have OpenSearch deployed for Global Search feature on dashboard , the `/health/ready` ( deep health check ) API which checks health of all the underlying queryable resources fails because OpenSearch is not present. To make it optional based on the deployment type needs changes and should be dependent on a config which should be given out on time of router deployment Currently if you don't have OpenSearch Deployment and have router running ```bash curl http://localhost:8080/health/ready -v * Host localhost:8080 was resolved. * IPv6: ::1 * IPv4: 127.0.0.1 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying [::1]:8080... * Connected to localhost (::1) port 8080 > GET /health/ready HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/8.7.1 > Accept: */* > * Request completely sent off < HTTP/1.1 500 Internal Server Error < content-length: 136 < access-control-expose-headers: x-request-id, content-type, via, strict-transport-security < via: HyperSwitch < x-request-id: 019634f7-a837-7d50-9a50-bb8e7651bd62 < content-type: application/json < vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers < strict-transport-security: max-age=31536000 < date: Mon, 14 Apr 2025 15:42:47 GMT < { [136 bytes data] 100 136 100 136 0 0 7613 0 --:--:-- --:--:-- --:--:-- 8000 * Connection #0 to host localhost left intact { "error": { "type": "api", "message": "Opensearch health check failed with error: Error while executing query in Opensearch", "code": "HE_00" } } ``` ## 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 http://localhost:8080/health/ready -v | jq . * Host localhost:8080 was resolved. * IPv6: ::1 * IPv4: 127.0.0.1 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying [::1]:8080... * Connected to localhost (::1) port 8080 > GET /health/ready HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/8.7.1 > Accept: */* > * Request completely sent off < HTTP/1.1 200 OK < content-length: 90 < content-type: application/json < x-request-id: 01963e0a-e41d-7251-b20a-e9a0a6d1a67a < vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers < access-control-expose-headers: content-type, strict-transport-security, x-request-id, via < strict-transport-security: max-age=31536000 < via: HyperSwitch < date: Wed, 16 Apr 2025 10:00:23 GMT < { [90 bytes data] 100 90 100 90 0 0 236 0 --:--:-- --:--:-- --:--:-- 236 * Connection #0 to host localhost left intact { "database": true, "redis": true, "analytics": true, "opensearch": false, "outgoing_request": true } ``` ## 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.113.0
c58e93bfdba4cbd70d69e6d3947e0e1c68504e7e
c58e93bfdba4cbd70d69e6d3947e0e1c68504e7e
juspay/hyperswitch
juspay__hyperswitch-7796
Bug: open router integration of success rate based routing add an api integration with open-router service. * decide-gateway * update-gateway-score
diff --git a/config/config.example.toml b/config/config.example.toml index 11d64093ab6..0ff30da45f4 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -969,4 +969,8 @@ primary_color = "#006DF9" background_color = "#FFFFFF" # Email background color [billing_connectors_payment_sync] -billing_connectors_which_require_payment_sync = "stripebilling, recurly" # List of billing connectors which has payment sync api call \ No newline at end of file +billing_connectors_which_require_payment_sync = "stripebilling, recurly" # List of billing connectors which has payment sync api call + +[open_router] +enabled = true # Enable or disable Open Router +url = "http://localhost:8080" # Open Router URL diff --git a/config/development.toml b/config/development.toml index 535850f0d9b..b2a9f7c7cbd 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1033,3 +1033,7 @@ background_color = "#FFFFFF" [platform] enabled = true + +[open_router] +enabled = false +url = "http://localhost:8080" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index c8d01502899..05685fcc5fc 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -788,9 +788,9 @@ enabled = false global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } [multitenancy.tenants.public] -base_url = "http://localhost:8080" -schema = "public" -accounts_schema = "public" +base_url = "http://localhost:8080" +schema = "public" +accounts_schema = "public" redis_key_prefix = "" clickhouse_database = "default" @@ -874,3 +874,6 @@ background_color = "#FFFFFF" [platform] enabled = true + +[open_router] +enabled = false diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index 171bcb67753..1d5bfd58467 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -23,6 +23,8 @@ pub mod gsm; pub mod health_check; pub mod locker_migration; pub mod mandates; +#[cfg(feature = "dynamic_routing")] +pub mod open_router; pub mod organization; pub mod payment_methods; pub mod payments; diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs new file mode 100644 index 00000000000..c33365df169 --- /dev/null +++ b/crates/api_models/src/open_router.rs @@ -0,0 +1,122 @@ +use std::{collections::HashMap, fmt::Debug}; + +use common_utils::{id_type, types::MinorUnit}; +pub use euclid::{ + dssa::types::EuclidAnalysable, + frontend::{ + ast, + dir::{DirKeyKind, EuclidDirFilter}, + }, +}; +use serde::{Deserialize, Serialize}; + +use crate::enums::{Currency, PaymentMethod, RoutableConnectors}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OpenRouterDecideGatewayRequest { + pub payment_info: PaymentInfo, + pub merchant_id: id_type::ProfileId, + pub eligible_gateway_list: Option<Vec<RoutableConnectors>>, + pub ranking_algorithm: Option<RankingAlgorithm>, + pub elimination_enabled: Option<bool>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum RankingAlgorithm { + SrBasedRouting, + PlBasedRouting, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentInfo { + pub payment_id: id_type::PaymentId, + pub amount: MinorUnit, + pub currency: Currency, + // customerId: Option<ETCu::CustomerId>, + // preferredGateway: Option<ETG::Gateway>, + pub payment_type: String, + // metadata: Option<String>, + // internalMetadata: Option<String>, + // isEmi: Option<bool>, + // emiBank: Option<String>, + // emiTenure: Option<i32>, + pub payment_method_type: String, + pub payment_method: PaymentMethod, + // paymentSource: Option<String>, + // authType: Option<ETCa::txn_card_info::AuthType>, + // cardIssuerBankName: Option<String>, + // cardIsin: Option<String>, + // cardType: Option<ETCa::card_type::CardType>, + // cardSwitchProvider: Option<Secret<String>>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct DecidedGateway { + pub gateway_priority_map: Option<HashMap<String, f64>>, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct ErrorResponse { + pub status: String, + pub error_code: String, + pub error_message: String, + pub priority_logic_tag: Option<String>, + pub filter_wise_gateways: Option<serde_json::Value>, + pub error_info: UnifiedError, + pub is_dynamic_mga_enabled: bool, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct UnifiedError { + pub code: String, + pub user_message: String, + pub developer_message: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct UpdateScorePayload { + pub merchant_id: id_type::ProfileId, + pub gateway: RoutableConnectors, + pub status: TxnStatus, + pub payment_id: id_type::PaymentId, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum TxnStatus { + Started, + AuthenticationFailed, + JuspayDeclined, + PendingVBV, + VBVSuccessful, + Authorized, + AuthorizationFailed, + Charged, + Authorizing, + CODInitiated, + Voided, + VoidInitiated, + Nop, + CaptureInitiated, + CaptureFailed, + VoidFailed, + AutoRefunded, + PartialCharged, + ToBeCharged, + Pending, + Failure, + Declined, +} + +impl From<bool> for TxnStatus { + fn from(value: bool) -> Self { + match value { + true => Self::Charged, + _ => Self::Failure, + } + } +} diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 7cd4ce2d4bd..1dfaf1e84ac 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -550,5 +550,6 @@ pub(crate) async fn fetch_raw_secrets( network_tokenization_supported_connectors: conf.network_tokenization_supported_connectors, theme: conf.theme, platform: conf.platform, + open_router: conf.open_router, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 83591b15e36..de0bafcdd3d 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -139,8 +139,14 @@ pub struct Settings<S: SecretState> { pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors, pub theme: ThemeSettings, pub platform: Platform, + pub open_router: OpenRouter, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct OpenRouter { + pub enabled: bool, + pub url: String, +} #[derive(Debug, Deserialize, Clone, Default)] pub struct Platform { pub enabled: bool, diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index a574d84fdcb..622802a5b0a 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -407,6 +407,10 @@ pub enum RoutingError { ContractRoutingClientInitializationError, #[error("Invalid contract based connector label received from dynamic routing service: '{0}'")] InvalidContractBasedConnectorLabel(String), + #[error("Failed to perform {algo} in open_router")] + OpenRouterCallFailed { algo: String }, + #[error("Error from open_router: {0}")] + OpenRouterError(String), } #[derive(Debug, Clone, thiserror::Error)] diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 38f4823e068..40b2e34d612 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -7268,6 +7268,9 @@ where .await .change_context(errors::ApiErrorResponse::InternalServerError)?; + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] + let payment_attempt = transaction_data.payment_attempt.clone(); + let connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), key_store, @@ -7282,33 +7285,42 @@ where // dynamic success based connector selection #[cfg(all(feature = "v1", feature = "dynamic_routing"))] - let connectors = { - if let Some(algo) = business_profile.dynamic_routing_algorithm.clone() { - let dynamic_routing_config: api_models::routing::DynamicRoutingAlgorithmRef = algo - .parse_value("DynamicRoutingAlgorithmRef") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?; - let dynamic_split = api_models::routing::RoutingVolumeSplit { - routing_type: api_models::routing::RoutingType::Dynamic, - split: dynamic_routing_config - .dynamic_routing_volume_split - .unwrap_or_default(), + let connectors = if let Some(algo) = business_profile.dynamic_routing_algorithm.clone() { + let dynamic_routing_config: api_models::routing::DynamicRoutingAlgorithmRef = algo + .parse_value("DynamicRoutingAlgorithmRef") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?; + let dynamic_split = api_models::routing::RoutingVolumeSplit { + routing_type: api_models::routing::RoutingType::Dynamic, + split: dynamic_routing_config + .dynamic_routing_volume_split + .unwrap_or_default(), + }; + let static_split: api_models::routing::RoutingVolumeSplit = + api_models::routing::RoutingVolumeSplit { + routing_type: api_models::routing::RoutingType::Static, + split: consts::DYNAMIC_ROUTING_MAX_VOLUME + - dynamic_routing_config + .dynamic_routing_volume_split + .unwrap_or_default(), }; - let static_split: api_models::routing::RoutingVolumeSplit = - api_models::routing::RoutingVolumeSplit { - routing_type: api_models::routing::RoutingType::Static, - split: consts::DYNAMIC_ROUTING_MAX_VOLUME - - dynamic_routing_config - .dynamic_routing_volume_split - .unwrap_or_default(), - }; - let volume_split_vec = vec![dynamic_split, static_split]; - let routing_choice = - routing::perform_dynamic_routing_volume_split(volume_split_vec, None) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to perform volume split on routing type")?; + let volume_split_vec = vec![dynamic_split, static_split]; + let routing_choice = routing::perform_dynamic_routing_volume_split(volume_split_vec, None) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to perform volume split on routing type")?; - if routing_choice.routing_type.is_dynamic_routing() { + if routing_choice.routing_type.is_dynamic_routing() { + if state.conf.open_router.enabled { + routing::perform_open_routing( + state, + connectors.clone(), + business_profile, + payment_attempt, + ) + .await + .map_err(|e| logger::error!(open_routing_error=?e)) + .unwrap_or(connectors) + } else { let dynamic_routing_config_params_interpolator = routing_helpers::DynamicRoutingConfigParamsInterpolator::new( payment_data.get_payment_attempt().payment_method, @@ -7350,12 +7362,12 @@ where .await .map_err(|e| logger::error!(dynamic_routing_error=?e)) .unwrap_or(connectors) - } else { - connectors } } else { connectors } + } else { + connectors }; let connector_data = connectors diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 889525ec6d5..4db49e8d44f 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -6,15 +6,21 @@ use std::collections::hash_map; use std::hash::{Hash, Hasher}; use std::{collections::HashMap, str::FromStr, sync::Arc}; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use api_models::routing as api_routing; use api_models::{ admin as admin_api, enums::{self as api_enums, CountryAlpha2}, routing::ConnectorSelection, }; -#[cfg(feature = "dynamic_routing")] -use common_utils::ext_traits::AsyncExt; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use api_models::{ + open_router::{self as or_types, DecidedGateway, OpenRouterDecideGatewayRequest}, + routing as api_routing, +}; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use common_utils::{ + ext_traits::{AsyncExt, BytesExt}, + request, +}; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use euclid::{ @@ -48,11 +54,10 @@ use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE}; use crate::core::admin; #[cfg(feature = "payouts")] use crate::core::payouts; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use crate::{core::routing::transformers::OpenRouterDecideGatewayRequestExt, headers, services}; use crate::{ - core::{ - errors, errors as oss_errors, - routing::{self}, - }, + core::{errors, errors as oss_errors, routing}, logger, types::{ api::{self, routing as routing_types}, @@ -1484,6 +1489,53 @@ pub fn make_dsl_input_for_surcharge( Ok(backend_input) } +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub async fn perform_open_routing( + state: &SessionState, + routable_connectors: Vec<api_routing::RoutableConnectorChoice>, + profile: &domain::Profile, + payment_data: oss_storage::PaymentAttempt, +) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { + let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile + .dynamic_routing_algorithm + .clone() + .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) + .transpose() + .change_context(errors::RoutingError::DeserializationError { + from: "JSON".to_string(), + to: "DynamicRoutingAlgorithmRef".to_string(), + }) + .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")? + .ok_or(errors::RoutingError::GenericNotFoundError { + field: "dynamic_routing_algorithm".to_string(), + })?; + + logger::debug!( + "performing dynamic_routing with open_router for profile {}", + profile.get_id().get_string_repr() + ); + + let connectors = dynamic_routing_algo_ref + .success_based_algorithm + .async_map(|algo| { + perform_success_based_routing_with_open_router( + state, + routable_connectors.clone(), + profile.get_id(), + algo, + payment_data, + ) + }) + .await + .transpose() + .inspect_err(|e| logger::error!(dynamic_routing_error=?e)) + .ok() + .flatten() + .unwrap_or(routable_connectors); + + Ok(connectors) +} + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn perform_dynamic_routing( state: &SessionState, @@ -1555,6 +1607,165 @@ pub async fn perform_dynamic_routing( Ok(connector_list) } +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[instrument(skip_all)] +pub async fn perform_success_based_routing_with_open_router( + state: &SessionState, + mut routable_connectors: Vec<api_routing::RoutableConnectorChoice>, + profile_id: &common_utils::id_type::ProfileId, + success_based_algo_ref: api_routing::SuccessBasedAlgorithm, + payment_attempt: oss_storage::PaymentAttempt, +) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { + if success_based_algo_ref.enabled_feature + == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection + { + logger::debug!( + "performing success_based_routing with open_router for profile {}", + profile_id.get_string_repr() + ); + + let open_router_req_body = OpenRouterDecideGatewayRequest::construct_sr_request( + payment_attempt, + routable_connectors + .iter() + .map(|gateway| gateway.connector) + .collect::<Vec<_>>(), + Some(or_types::RankingAlgorithm::SrBasedRouting), + ); + + let url = format!("{}/{}", &state.conf.open_router.url, "decide-gateway"); + let mut request = request::Request::new(services::Method::Post, &url); + request.add_header(headers::CONTENT_TYPE, "application/json".into()); + request.add_header( + headers::X_TENANT_ID, + state.tenant.tenant_id.get_string_repr().to_owned().into(), + ); + request.set_body(request::RequestContent::Json(Box::new( + open_router_req_body, + ))); + + let response = services::call_connector_api(state, request, "open_router_sr_call") + .await + .change_context(errors::RoutingError::OpenRouterCallFailed { + algo: "success_rate".into(), + })?; + + let sr_sorted_connectors = match response { + Ok(resp) => { + let decided_gateway: DecidedGateway = resp + .response + .parse_struct("DecidedGateway") + .change_context(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ))?; + + if let Some(gateway_priority_map) = decided_gateway.gateway_priority_map { + logger::debug!( + "Open router gateway_priority_map response: {:?}", + gateway_priority_map + ); + routable_connectors.sort_by(|connector_choice_a, connector_choice_b| { + let connector_choice_a_score = gateway_priority_map + .get(&connector_choice_a.connector.to_string()) + .copied() + .unwrap_or(0.0); + let connector_choice_b_score = gateway_priority_map + .get(&connector_choice_b.connector.to_string()) + .copied() + .unwrap_or(0.0); + connector_choice_b_score + .partial_cmp(&connector_choice_a_score) + .unwrap_or(std::cmp::Ordering::Equal) + }); + } + Ok(routable_connectors) + } + Err(err) => { + let err_resp: or_types::ErrorResponse = err + .response + .parse_struct("ErrorResponse") + .change_context(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ))?; + logger::error!("open_router_error_response: {:?}", err_resp); + Err(errors::RoutingError::OpenRouterError( + "Failed to perform success based routing in open router".into(), + )) + } + }?; + + Ok(sr_sorted_connectors) + } else { + Ok(routable_connectors) + } +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[instrument(skip_all)] +pub async fn update_success_rate_score_with_open_router( + state: &SessionState, + payment_connector: common_enums::RoutableConnectors, + profile_id: &common_utils::id_type::ProfileId, + payment_id: &common_utils::id_type::PaymentId, + payment_status: bool, +) -> RoutingResult<()> { + let open_router_req_body = or_types::UpdateScorePayload { + merchant_id: profile_id.clone(), + gateway: payment_connector, + status: payment_status.into(), + payment_id: payment_id.clone(), + }; + + let url = format!("{}/{}", &state.conf.open_router.url, "update-gateway-score"); + let mut request = request::Request::new(services::Method::Post, &url); + request.add_header(headers::CONTENT_TYPE, "application/json".into()); + request.add_header( + headers::X_TENANT_ID, + state.tenant.tenant_id.get_string_repr().to_owned().into(), + ); + request.set_body(request::RequestContent::Json(Box::new( + open_router_req_body, + ))); + + let response = + services::call_connector_api(state, request, "open_router_update_gateway_score_call") + .await + .change_context(errors::RoutingError::OpenRouterCallFailed { + algo: "success_rate".into(), + })?; + + match response { + Ok(resp) => { + let update_score_resp = String::from_utf8(resp.response.to_vec()).change_context( + errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ), + )?; + + logger::debug!( + "Open router update_gateway_score response: {:?}", + update_score_resp + ); + + Ok(()) + } + Err(err) => { + let err_resp: or_types::ErrorResponse = err + .response + .parse_struct("ErrorResponse") + .change_context(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ))?; + logger::error!("open_router_error_response: {:?}", err_resp); + Err(errors::RoutingError::OpenRouterError( + "Failed to update gateway score for success based routing in open router".into(), + )) + } + }?; + + Ok(()) +} + /// success based dynamic routing #[cfg(all(feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index ec86102eba0..6bb0ba5878f 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -46,7 +46,10 @@ use crate::{ utils::StringExt, }; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] -use crate::{core::metrics as core_metrics, types::transformers::ForeignInto}; +use crate::{ + core::{metrics as core_metrics, routing}, + types::transformers::ForeignInto, +}; pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = "Success rate based dynamic routing algorithm"; pub const ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = @@ -688,6 +691,28 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( }, )?; + let payment_status_attribute = + get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status); + + let should_route_to_open_router = state.conf.open_router.enabled; + + if should_route_to_open_router { + routing::payments_routing::update_success_rate_score_with_open_router( + state, + common_enums::RoutableConnectors::from_str(payment_connector.as_str()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to infer routable_connector from connector")?, + profile_id, + &payment_attempt.payment_id, + payment_status_attribute == common_enums::AttemptStatus::Charged, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to update gateway score in open router service")?; + + return Ok(()); + } + let success_based_routing_configs = fetch_dynamic_routing_configs::< routing_types::SuccessBasedRoutingConfig, >( @@ -732,9 +757,6 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( "unable to calculate/fetch success rate from dynamic routing service", )?; - let payment_status_attribute = - get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status); - let first_merchant_success_based_connector = &success_based_connectors .entity_scores_with_labels .first() @@ -932,6 +954,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( .attach_printable( "unable to update success based routing window in dynamic routing service", )?; + Ok(()) } else { Ok(()) diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rs index 652422086b7..d73e0d28671 100644 --- a/crates/router/src/core/routing/transformers.rs +++ b/crates/router/src/core/routing/transformers.rs @@ -1,12 +1,18 @@ +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use api_models::open_router::{OpenRouterDecideGatewayRequest, PaymentInfo, RankingAlgorithm}; use api_models::routing::{ MerchantRoutingAlgorithm, RoutingAlgorithm as Algorithm, RoutingAlgorithmKind, RoutingDictionaryRecord, }; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use common_enums::RoutableConnectors; use common_utils::ext_traits::ValueExt; use diesel_models::{ enums as storage_enums, routing_algorithm::{RoutingAlgorithm, RoutingProfileMetadata}, }; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt; use crate::{ core::{errors, routing}, @@ -98,3 +104,39 @@ impl From<&routing::TransactionData<'_>> for storage_enums::TransactionType { } } } + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub trait OpenRouterDecideGatewayRequestExt { + fn construct_sr_request( + attempt: PaymentAttempt, + eligible_gateway_list: Vec<RoutableConnectors>, + ranking_algorithm: Option<RankingAlgorithm>, + ) -> Self + where + Self: Sized; +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest { + fn construct_sr_request( + attempt: PaymentAttempt, + eligible_gateway_list: Vec<RoutableConnectors>, + ranking_algorithm: Option<RankingAlgorithm>, + ) -> Self { + Self { + payment_info: PaymentInfo { + payment_id: attempt.payment_id, + amount: attempt.net_amount.get_order_amount(), + currency: attempt.currency.unwrap_or(storage_enums::Currency::USD), + payment_type: "ORDER_PAYMENT".to_string(), + // payment_method_type: attempt.payment_method_type.clone().unwrap(), + payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt + payment_method: attempt.payment_method.unwrap_or_default(), + }, + merchant_id: attempt.profile_id, + eligible_gateway_list: Some(eligible_gateway_list), + ranking_algorithm, + elimination_enabled: None, + } + } +}
2025-04-11T09:33:58Z
## 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 an api integration with open-router service. * decide-gateway * update-gateway-score ### 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 merchant_account, api_key, mca 1. Enable SR for merchant ``` curl --location --request POST 'http://localhost:8080/account/merchant_1744368166/business_profile/pro_GrzjTHd5Pn5hAhwTZPRn/dynamic_routing/success_based/toggle?enable=dynamic_connector_selection' \ --header 'api-key: dev_a4XMpNXd3Yriz5DPsiwU6UbxEkiRkXdqHhwnJPolnVhssLaDEbOg6f5kE6B2hx1f' ``` 2. Enable Volume split ``` curl --location --request POST 'http://localhost:8080/account/merchant_1744368166/business_profile/pro_GrzjTHd5Pn5hAhwTZPRn/dynamic_routing/set_volume_split?split=100' \ --header 'api-key: dev_a4XMpNXd3Yriz5DPsiwU6UbxEkiRkXdqHhwnJPolnVhssLaDEbOg6f5kE6B2hx1f' ``` 3. Create a Payment Search for the log "Open router gateway_priority_map response" <img width="1360" alt="image" src="https://github.com/user-attachments/assets/b7c8e95e-3661-4097-bd25-3072148449ed" /> <img width="1364" alt="image" src="https://github.com/user-attachments/assets/be8ad1d1-38a8-408f-99c6-82816ae202fe" /> ## 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.113.0
e677b1389f7ab2518f176e5c5cfcba44fc185bbc
e677b1389f7ab2518f176e5c5cfcba44fc185bbc
juspay/hyperswitch
juspay__hyperswitch-7792
Bug: Point v2 to v1 dashboard_metadata table Point v2 to v1 dashboard_metadata table Move dashboard_metadata into accounts_schema.
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index d98f834e7b5..34e9fb4530b 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -169,6 +169,7 @@ pub trait AccountsStorageInterface: + business_profile::ProfileInterface + merchant_connector_account::MerchantConnectorAccountInterface + merchant_key_store::MerchantKeyStoreInterface + + dashboard_metadata::DashboardMetadataInterface + 'static { } diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rs index 4f1624f3457..1b6b7417ded 100644 --- a/crates/router/src/db/dashboard_metadata.rs +++ b/crates/router/src/db/dashboard_metadata.rs @@ -62,7 +62,7 @@ impl DashboardMetadataInterface for Store { &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_accounts_connection_write(self).await?; metadata .insert(&conn) .await @@ -78,7 +78,7 @@ impl DashboardMetadataInterface for Store { data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_accounts_connection_write(self).await?; storage::DashboardMetadata::update( &conn, user_id, @@ -99,7 +99,7 @@ impl DashboardMetadataInterface for Store { org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { - let conn = connection::pg_connection_read(self).await?; + let conn = connection::pg_accounts_connection_read(self).await?; storage::DashboardMetadata::find_user_scoped_dashboard_metadata( &conn, user_id.to_owned(), @@ -118,7 +118,7 @@ impl DashboardMetadataInterface for Store { org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { - let conn = connection::pg_connection_read(self).await?; + let conn = connection::pg_accounts_connection_read(self).await?; storage::DashboardMetadata::find_merchant_scoped_dashboard_metadata( &conn, merchant_id.to_owned(), @@ -135,7 +135,7 @@ impl DashboardMetadataInterface for Store { user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_accounts_connection_write(self).await?; storage::DashboardMetadata::delete_all_user_scoped_dashboard_metadata_by_merchant_id( &conn, user_id.to_owned(), @@ -152,7 +152,7 @@ impl DashboardMetadataInterface for Store { merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_accounts_connection_write(self).await?; storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &conn, user_id.to_owned(),
2025-04-10T18:26:41Z
## 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 moves the dashboard_metadata table to `accounts_schema` and points v2 to the v1 public schema - dashboard_metadata 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). --> To store all the data regarding dashboard_metadata in a common table irrespective of v1 and v2. ## 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 by deploying this branch on v2 integ-router and hitting the following 2 API's. The entries from the POST API populated the integ v1 public schema - dashboard metadata table. <img width="1728" alt="image" src="https://github.com/user-attachments/assets/2b73d3ff-2055-438c-a7d6-f1d865b57403" /> The highlighted entry in the v1 public schema dashboard_metadata table is the entry populated by hitting the v2 API, given by the curl below. Hit the following curl: - The entry for ProdIntent should be created in v1 public schema - dashboard_metadata table. ```bash curl --location 'http://localhost:8080/v2/user/data' \ --header 'accept: */*' \ --header 'accept-language: en-US,en;q=0.9' \ --header 'api-key: hyperswitch' \ --header 'content-type: application/json' \ --header 'origin: https://app.hyperswitch.io' \ --header 'priority: u=1, i' \ --header 'referer: https://app.hyperswitch.io/dashboard/home' \ --header 'sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'sec-fetch-dest: empty' \ --header 'sec-fetch-mode: cors' \ --header 'sec-fetch-site: same-origin' \ --header 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' \ --header 'x-merchant-id: merchant_1715600622' \ --header 'x-profile-id: pro_CqAdpUQBUUam1n0g56mB' \ --header 'cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNjY2YzZlYWQtMWUzZi00ZTY4LWI5NjQtMGNiZTdkMWQ0OTk4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjkzMzU5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDQ2NjE2Niwib3JnX2lkIjoib3JnX0hzNWNLM0RlSDByRTJGcTMwSmp5IiwicHJvZmlsZV9pZCI6InByb190Nml0cjE3TkR3cWJOdHV5OG44diIsInRlbmFudF9pZCI6InB1YmxpYyJ9.sckbBxvWK6MtuAAoi4rZaeOwfU2AibyLz8GR7ZcF0pc' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNjY2YzZlYWQtMWUzZi00ZTY4LWI5NjQtMGNiZTdkMWQ0OTk4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjkzMzU5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDQ2NjE2Niwib3JnX2lkIjoib3JnX0hzNWNLM0RlSDByRTJGcTMwSmp5IiwicHJvZmlsZV9pZCI6InByb190Nml0cjE3TkR3cWJOdHV5OG44diIsInRlbmFudF9pZCI6InB1YmxpYyJ9.sckbBxvWK6MtuAAoi4rZaeOwfU2AibyLz8GR7ZcF0pc' \ --data-raw '{ "ProdIntent": { "poc_email": "[email protected]", "is_completed": true, "legal_business_name": "blueberry", "business_location": "IN", "business_website": "https://google.com", "poc_name": "berry", "comments": "tx123", "product_type": "vault" } }' ``` Expected Response: 200 OK, no body in the response The following curl is supposed to read data from v1 public schema dashboard_metadata table and return the entry whether or not a prod_intent has been raised for a particular merchant_account. ```bash curl --location 'http://localhost:8080/v2/user/data?keys=ProdIntent' \ --header 'X-Merchant-Id: ddcd_oBuAVsHl0XMLag9JsHCV' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiM2RlMDFhYWYtOWVkMi00YTY5LTg3YWItNWU1YmI2ZWFiNGQ5IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQyMjEyMzQxIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Mjk4MDgyOCwib3JnX2lkIjoib3JnX3pMQmRNTnpLaDZrNmhiT2tockdJIiwicHJvZmlsZV9pZCI6InByb19LWnhHZ21rUHFkMldQdXBFa2psWCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.aD185AZEOcIjHnLnZZ9GJ2ujSHIdRPbPtrYhzNo0V4M' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'Referer: https://integ.hyperswitch.io/dashboard/v2/recon' \ --header 'sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"' \ --header 'X-Profile-Id: pro_UaxaxwTw4A0a9D0QNBrf' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'api-key: hyperswitch' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' ``` Expected Response: ```json [ { "ProdIntent": { "legal_business_name": "blueberry", "business_label": null, "business_location": "IN", "display_name": null, "poc_email": "[email protected]", "business_type": null, "business_identifier": null, "business_website": "https://google.com", "poc_name": "berry", "poc_contact": null, "comments": "tx123", "is_completed": true, "product_type": "vault" } } ] ``` ## 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.113.0
c58e93bfdba4cbd70d69e6d3947e0e1c68504e7e
c58e93bfdba4cbd70d69e6d3947e0e1c68504e7e
juspay/hyperswitch
juspay__hyperswitch-7794
Bug: [ENHANCEMENT] update payments API response This issue is around two specific fields in the payments API 1. Payments response -`error_code` and `error_message` HyperSwitch should not propagate the intermediary dummy error codes and error messages to the API response. Currently, `ErrorResponse` in connector integration mandates setting an error_code and error_message. But some connectors might not have this available during transaction failures. For this reason, current HyperSwitch integration uses NO_ERROR_CODE for `error_code` and NO_ERROR_MESSAGE for `error_message`. These are constant strings which are propagated from connector integration to core layer and later sent back in the response. It doesn't make sense to have these in the API response as HyperSwitch should not 'invent' new codes and messages. This should be removed from the API response in such cases. 2. Payments request - `return_url` HyperSwitch should always validate the presence of `return_url` during payment link creation as it is a required field in payment link flows.
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index f7167a607a2..7ce8ed6d710 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -892,11 +892,11 @@ impl<F> code: non_threeds_data .error_code .clone() - .unwrap_or_else(|| "NO_ERROR_CODE".to_string()), + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: non_threeds_data .error_desc .clone() - .unwrap_or_else(|| "NO_ERROR_MESSAGE".to_string()), + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: non_threeds_data.error_desc.clone(), status_code: item.http_code, attempt_status: None, @@ -941,11 +941,11 @@ impl<F> code: recurring_response .reason .clone() - .unwrap_or_else(|| "NO_ERROR_CODE".to_string()), + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: recurring_response .reason .clone() - .unwrap_or_else(|| "NO_ERROR_MESSAGE".to_string()), + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: recurring_response.reason.clone(), status_code: item.http_code, attempt_status: None, @@ -1480,19 +1480,17 @@ impl TryFrom<PaymentsCaptureResponseRouterData<PaymentCaptureResponse>> }?; let capture_message_status = capture_status_codes(); let error_response = if status == enums::AttemptStatus::Failure { + let optional_message = capture_message_status + .get(status_code.as_str()) + .copied() + .map(String::from); Some(ErrorResponse { status_code: item.http_code, code: status_code.to_owned(), - message: capture_message_status - .get(status_code.as_str()) - .unwrap_or(&"NO_ERROR_MESSAGE") - .to_string(), - reason: Some( - capture_message_status - .get(status_code.as_str()) - .unwrap_or(&"NO_ERROR_REASON") - .to_string(), - ), + message: optional_message + .clone() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: optional_message, attempt_status: None, connector_transaction_id: Some(item.response.tran_id.clone()), network_advice_code: None, @@ -1596,19 +1594,18 @@ impl TryFrom<PaymentsCancelResponseRouterData<FiuuPaymentCancelResponse>> }?; let void_message_status = void_status_codes(); let error_response = if status == enums::AttemptStatus::VoidFailed { + let optional_message = void_message_status + .get(status_code.as_str()) + .copied() + .map(String::from); + Some(ErrorResponse { status_code: item.http_code, code: status_code.to_owned(), - message: void_message_status - .get(status_code.as_str()) - .unwrap_or(&"NO_ERROR_MESSAGE") - .to_string(), - reason: Some( - void_message_status - .get(status_code.as_str()) - .unwrap_or(&"NO_ERROR_REASON") - .to_string(), - ), + message: optional_message + .clone() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: optional_message, attempt_status: None, connector_transaction_id: Some(item.response.tran_id.clone()), network_advice_code: None, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 077a288c167..3001776cbfd 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2075,6 +2075,8 @@ where { use std::ops::Not; + use hyperswitch_interfaces::consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}; + let payment_attempt = payment_data.get_payment_attempt().clone(); let payment_intent = payment_data.get_payment_intent().clone(); let payment_link_data = payment_data.get_payment_link_data(); @@ -2561,10 +2563,13 @@ where statement_descriptor_suffix: payment_intent.statement_descriptor_suffix, next_action: next_action_response, cancellation_reason: payment_attempt.cancellation_reason, - error_code: payment_attempt.error_code, + error_code: payment_attempt + .error_code + .filter(|code| code != NO_ERROR_CODE), error_message: payment_attempt .error_reason - .or(payment_attempt.error_message), + .or(payment_attempt.error_message) + .filter(|message| message != NO_ERROR_MESSAGE), unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, payment_experience: payment_attempt.payment_experience,
2025-04-11T15:01:31Z
## 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 filters the `error_code` and `error_message` in Payments API response to ensure HyperSwitch does not send back any 'invented' codes or messages. This is achieved by filtering such error codes and error messages are not sent back in the API response. Details in ticket - https://github.com/juspay/hyperswitch/issues/7794 (point # 1) ### 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 ensures HyperSwitch does not invent any new error codes or messages and send it back in the Payments API response. In case error codes and messages are not present, it will send back null in the response ## How did you test it? <details> <summary>1. Create card payment via Nexixpay (failed card txn)</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ddmeaxUlgRPHkcqtmZZm5nGMRhejMxXijYCnsp070Oqn2y4lrfUNBCb9UmedwgMt' \ --data-raw '{"amount":3000,"currency":"EUR","confirm":true,"profile_id":"pro_510ieWUUX4pc0bUWmBW3","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","connector":["nexixpay"],"email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_data":{"card":{"card_number":"4349940199997007","card_exp_month":"12","card_exp_year":"28","card_holder_name":"joseph Doe","card_cvc":"829"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"IT","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":30,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"connector_metadata":{"noon":{"order_category":"pay"}},"session_expiry":60}' Response {"payment_id":"pay_CLMzDJcQecFlM3bTdeZQ","merchant_id":"merchant_1744368926","status":"requires_customer_action","amount":3000,"net_amount":3000,"shipping_cost":null,"amount_capturable":3000,"amount_received":null,"connector":"nexixpay","client_secret":"pay_CLMzDJcQecFlM3bTdeZQ_secret_WtxTUTQUXoYjF4Gt6f7a","created":"2025-04-11T14:28:21.682Z","currency":"EUR","customer_id":null,"customer":{"id":null,"name":null,"email":"[email protected]","phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"7007","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"434994","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"28","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":"token_KyWCvOf88BnnPydHsewF","shipping":null,"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":{"type":"redirect_to_url","redirect_to_url":"https://tame-bird-39.telebit.io/payments/redirect/pay_CLMzDJcQecFlM3bTdeZQ/merchant_1744368926/pay_CLMzDJcQecFlM3bTdeZQ_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":null,"connector_transaction_id":"pay_CLMzDJcQecFlM3bTdeZQ_1","frm_message":null,"metadata":null,"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":{"order_category":"pay"},"braintree":null},"feature_metadata":null,"reference_id":"pay_CLMzDJcQecFlM3bTdeZQ_1","payment_link":null,"profile_id":"pro_510ieWUUX4pc0bUWmBW3","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_d4eEG4Vgv2liRzTtsWKM","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-11T14:29:21.682Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":30,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-11T14:28:22.739Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} Open the link and complete the payment </details> <details> <summary>2. Retrieve the payment</summary> cURL curl --location --request GET 'http://localhost:8080/payments/pay_CLMzDJcQecFlM3bTdeZQ?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_ddmeaxUlgRPHkcqtmZZm5nGMRhejMxXijYCnsp070Oqn2y4lrfUNBCb9UmedwgMt' Response {"payment_id":"pay_CLMzDJcQecFlM3bTdeZQ","merchant_id":"merchant_1744368926","status":"failed","amount":3000,"net_amount":3000,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"nexixpay","client_secret":"pay_CLMzDJcQecFlM3bTdeZQ_secret_WtxTUTQUXoYjF4Gt6f7a","created":"2025-04-11T14:28:21.682Z","currency":"EUR","customer_id":null,"customer":{"id":null,"name":null,"email":"[email protected]","phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"7007","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"434994","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"28","card_holder_name":"joseph Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":"token_KyWCvOf88BnnPydHsewF","shipping":null,"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":"Declined","unified_code":"UE_9000","unified_message":"Something went wrong","payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":true,"connector_transaction_id":"pay_CLMzDJcQecFlM3bTdeZQ_1","frm_message":null,"metadata":null,"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":{"order_category":"pay"},"braintree":null},"feature_metadata":null,"reference_id":"pay_CLMzDJcQecFlM3bTdeZQ_1","payment_link":null,"profile_id":"pro_510ieWUUX4pc0bUWmBW3","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_d4eEG4Vgv2liRzTtsWKM","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-11T14:29:21.682Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":30,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-11T14:28:32.770Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} Things to verify 1. Error code must be null for this scenario 2. Error code in DB must be `No error code` <img width="413" alt="Screenshot 2025-04-11 at 9 52 43 PM" src="https://github.com/user-attachments/assets/f756f6e3-77f7-4e0a-9a78-c97f686b7b30" /> </details> ## 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.113.0
4f4e31db24652e72ce50745e9d64618c93c692bc
4f4e31db24652e72ce50745e9d64618c93c692bc
juspay/hyperswitch
juspay__hyperswitch-7790
Bug: Modify List Merchant Accounts in Org with org_id (v1) hotfix Modify List Merchant Accounts in Org with org_id (v1) as v2 merchant accounts will hav merchant_id as Null, and they cant be deserialized into v1. This will cause terminate_2fa API to fail and cant obtain the merchant_id required to generate the jwt token.
diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rs index c40af7f6535..ab51953b6ef 100644 --- a/crates/diesel_models/src/query/merchant_account.rs +++ b/crates/diesel_models/src/query/merchant_account.rs @@ -1,4 +1,5 @@ -use diesel::{associations::HasTable, ExpressionMethods, Table}; +use common_types::consts::API_VERSION; +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; #[cfg(feature = "v1")] @@ -101,7 +102,9 @@ impl MerchantAccount { _, >( conn, - dsl::organization_id.eq(organization_id.to_owned()), + dsl::organization_id + .eq(organization_id.to_owned()) + .and(dsl::version.eq(API_VERSION)), None, None, None,
2025-04-10T13:41:31Z
## 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 --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7782](https://github.com/juspay/hyperswitch/pull/7782) ### 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.113.0
0a5d2495435ff737dd952c97e5dcd0fc52839258
0a5d2495435ff737dd952c97e5dcd0fc52839258
juspay/hyperswitch
juspay__hyperswitch-7789
Bug: ProdIntent Changes for v1 and v2 merchant accounts hotfix ProdIntent changes for providing context of product_type and also converting it into merchant-scope from user scope.
diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs index fa550d671fb..8e734d31b53 100644 --- a/crates/api_models/src/user/dashboard_metadata.rs +++ b/crates/api_models/src/user/dashboard_metadata.rs @@ -1,4 +1,4 @@ -use common_enums::CountryAlpha2; +use common_enums::{CountryAlpha2, MerchantProductType}; use common_utils::{id_type, pii}; use masking::Secret; use strum::EnumString; @@ -103,6 +103,8 @@ pub struct ProdIntent { pub poc_contact: Option<String>, pub comments: Option<String>, pub is_completed: bool, + #[serde(default)] + pub product_type: MerchantProductType, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] diff --git a/crates/common_enums/src/enums/accounts.rs b/crates/common_enums/src/enums/accounts.rs index d9c83312d6b..e5b3ef733c6 100644 --- a/crates/common_enums/src/enums/accounts.rs +++ b/crates/common_enums/src/enums/accounts.rs @@ -1,6 +1,7 @@ use serde; use utoipa::ToSchema; #[derive( + Copy, Default, Clone, Debug, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index b9ebdf13028..91b20621da8 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -2974,7 +2974,7 @@ pub async fn list_merchants_for_user_in_org( .map(|merchant_account| user_api::UserMerchantAccountResponse { merchant_name: merchant_account.merchant_name.clone(), merchant_id: merchant_account.get_id().to_owned(), - product_type: merchant_account.product_type.clone(), + product_type: merchant_account.product_type, version: merchant_account.version, }) .collect::<Vec<_>>(), diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index d79d155cba9..a4068fc4fad 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -38,7 +38,6 @@ pub async fn set_metadata( Ok(ApplicationResponse::StatusOk) } -#[cfg(feature = "v1")] pub async fn get_multiple_metadata( state: SessionState, user: UserFromToken, @@ -462,7 +461,7 @@ async fn insert_metadata( pii::Email::from_str(inner_poc_email) .change_context(UserErrors::EmailParsingError)?; } - let mut metadata = utils::insert_user_scoped_metadata_to_db( + let mut metadata = utils::insert_merchant_scoped_metadata_to_db( state, user.user_id.clone(), user.merchant_id.clone(), @@ -473,7 +472,7 @@ async fn insert_metadata( .await; if utils::is_update_required(&metadata) { - metadata = utils::update_user_scoped_metadata( + metadata = utils::update_merchant_scoped_metadata( state, user.user_id.clone(), user.merchant_id.clone(), @@ -500,7 +499,6 @@ async fn insert_metadata( EntityType::Merchant, ) .await?; - let email_contents = email_types::BizEmailProd::new( state, data, @@ -662,7 +660,6 @@ async fn fetch_metadata( Ok(dashboard_metadata) } -#[cfg(feature = "v1")] pub async fn backfill_metadata( state: &SessionState, user: &UserFromToken, @@ -705,6 +702,11 @@ pub async fn backfill_metadata( return Ok(None); }; + #[cfg(feature = "v1")] + let processor_name = mca.connector_name.clone(); + + #[cfg(feature = "v2")] + let processor_name = mca.connector_name.to_string().clone(); Some( insert_metadata( state, @@ -712,13 +714,14 @@ pub async fn backfill_metadata( DBEnum::StripeConnected, types::MetaData::StripeConnected(api::ProcessorConnected { processor_id: mca.get_id(), - processor_name: mca.connector_name, + processor_name, }), ) .await, ) .transpose() } + DBEnum::PaypalConnected => { let mca = if let Some(paypal_connected) = get_merchant_connector_account_by_name( state, @@ -745,6 +748,11 @@ pub async fn backfill_metadata( return Ok(None); }; + #[cfg(feature = "v1")] + let processor_name = mca.connector_name.clone(); + + #[cfg(feature = "v2")] + let processor_name = mca.connector_name.to_string().clone(); Some( insert_metadata( state, @@ -752,7 +760,7 @@ pub async fn backfill_metadata( DBEnum::PaypalConnected, types::MetaData::PaypalConnected(api::ProcessorConnected { processor_id: mca.get_id(), - processor_name: mca.connector_name, + processor_name, }), ) .await, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 2200567ddf9..1879d19de04 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2136,6 +2136,12 @@ impl User { ), ); + route = route.service( + web::resource("/data") + .route(web::get().to(user::get_multiple_dashboard_metadata)) + .route(web::post().to(user::set_dashboard_metadata)), + ); + route } } diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 1af22d0338a..d075048ddb6 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -197,7 +197,6 @@ pub async fn set_dashboard_metadata( .await } -#[cfg(feature = "v1")] pub async fn get_multiple_dashboard_metadata( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/services/email/assets/bizemailprod.html b/crates/router/src/services/email/assets/bizemailprod.html index 3645c953a02..2c973f2d622 100644 --- a/crates/router/src/services/email/assets/bizemailprod.html +++ b/crates/router/src/services/email/assets/bizemailprod.html @@ -104,6 +104,10 @@ <strong>Business Website:</strong> {business_website} </li> + <li> + <strong>Product Type:</strong> + {product_type} + </li> </ol> </td> </tr> diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 5f611bc1b3a..d663f72cec7 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,5 +1,5 @@ use api_models::user::dashboard_metadata::ProdIntent; -use common_enums::EntityType; +use common_enums::{EntityType, MerchantProductType}; use common_utils::{errors::CustomResult, pii, types::theme::EmailThemeConfig}; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; @@ -64,6 +64,7 @@ pub enum EmailBody { legal_business_name: String, business_location: String, business_website: String, + product_type: MerchantProductType, }, ReconActivation { user_name: String, @@ -199,6 +200,7 @@ pub mod html { legal_business_name, business_location, business_website, + product_type, } => { format!( include_str!("assets/bizemailprod.html"), @@ -207,6 +209,7 @@ pub mod html { business_location = business_location, business_website = business_website, username = user_name, + product_type = product_type ) } EmailBody::ProFeatureRequest { @@ -558,6 +561,7 @@ pub struct BizEmailProd { pub settings: std::sync::Arc<configs::Settings>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, + pub product_type: MerchantProductType, } impl BizEmailProd { @@ -582,6 +586,7 @@ impl BizEmailProd { business_website: data.business_website.unwrap_or_default(), theme_id, theme_config, + product_type: data.product_type, }) } } @@ -595,6 +600,7 @@ impl EmailData for BizEmailProd { legal_business_name: self.legal_business_name.clone(), business_location: self.business_location.clone(), business_website: self.business_website.clone(), + product_type: self.product_type, }); Ok(EmailContents { diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 4854d1b4786..8bf177035ef 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -417,7 +417,7 @@ impl NewUserMerchant { } pub fn get_product_type(&self) -> Option<common_enums::MerchantProductType> { - self.product_type.clone() + self.product_type } pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> { @@ -703,11 +703,18 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant { } else { id_type::MerchantId::new_from_unix_timestamp() }; + let (user_from_storage, user_merchant_create, user_from_token) = value; Ok(Self { merchant_id, - company_name: Some(UserCompanyName::new(value.1.company_name.clone())?), - product_type: value.1.product_type.clone(), - new_organization: NewUserOrganization::from(value), + company_name: Some(UserCompanyName::new( + user_merchant_create.company_name.clone(), + )?), + product_type: user_merchant_create.product_type, + new_organization: NewUserOrganization::from(( + user_from_storage, + user_merchant_create, + user_from_token, + )), }) } } diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs index c19b52b6f86..a91a3fe917b 100644 --- a/crates/router/src/utils/user/dashboard_metadata.rs +++ b/crates/router/src/utils/user/dashboard_metadata.rs @@ -218,10 +218,9 @@ pub fn separate_metadata_type_based_on_scope( | DBEnum::SetupWoocomWebhook | DBEnum::OnboardingSurvey | DBEnum::IsMultipleConfiguration - | DBEnum::ReconStatus => merchant_scoped.push(key), - DBEnum::Feedback | DBEnum::ProdIntent | DBEnum::IsChangePasswordRequired => { - user_scoped.push(key) - } + | DBEnum::ReconStatus + | DBEnum::ProdIntent => merchant_scoped.push(key), + DBEnum::Feedback | DBEnum::IsChangePasswordRequired => user_scoped.push(key), } } (merchant_scoped, user_scoped)
2025-04-10T13:41:15Z
## 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 --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7638](https://github.com/juspay/hyperswitch/pull/7638) ### 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.113.0
0676341b6bc34b26ec839c533664580b775e99a8
0676341b6bc34b26ec839c533664580b775e99a8
juspay/hyperswitch
juspay__hyperswitch-7791
Bug: refactor(gsm): introduce `feature` and `feature_data` to gsm Refactor gsm to add `feature` and `feature_data` columns so that it case used to introduce new features
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 3a84df8141f..e38d2cfa965 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -16000,7 +16000,8 @@ }, "step_up_possible": { "type": "boolean", - "description": "indicates if step_up retry is possible" + "description": "indicates if step_up retry is possible\n**Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.", + "deprecated": true }, "unified_code": { "type": "string", @@ -16022,7 +16023,24 @@ }, "clear_pan_possible": { "type": "boolean", - "description": "indicates if retry with pan is possible" + "description": "indicates if retry with pan is possible\n**Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.", + "deprecated": true + }, + "feature": { + "allOf": [ + { + "$ref": "#/components/schemas/GsmFeature" + } + ], + "nullable": true + }, + "feature_data": { + "allOf": [ + { + "$ref": "#/components/schemas/GsmFeatureData" + } + ], + "nullable": true } } }, @@ -16030,7 +16048,6 @@ "type": "string", "enum": [ "retry", - "requeue", "do_default" ] }, @@ -16097,6 +16114,28 @@ } } }, + "GsmFeature": { + "type": "string", + "enum": [ + "retry" + ] + }, + "GsmFeatureData": { + "oneOf": [ + { + "type": "object", + "required": [ + "retry" + ], + "properties": { + "retry": { + "$ref": "#/components/schemas/RetryFeatureData" + } + } + } + ], + "description": "Contains the data relevant to the specified GSM feature, if applicable.\nFor example, if the `feature` is `Retry`, this will include configuration\ndetails specific to the retry behavior." + }, "GsmResponse": { "type": "object", "required": [ @@ -16108,7 +16147,9 @@ "status", "decision", "step_up_possible", - "clear_pan_possible" + "clear_pan_possible", + "feature", + "feature_data" ], "properties": { "connector": { @@ -16141,12 +16182,12 @@ "nullable": true }, "decision": { - "type": "string", - "description": "decision to be taken for auto retries flow" + "$ref": "#/components/schemas/GsmDecision" }, "step_up_possible": { "type": "boolean", - "description": "indicates if step_up retry is possible" + "description": "indicates if step_up retry is possible\n**Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.", + "deprecated": true }, "unified_code": { "type": "string", @@ -16168,7 +16209,14 @@ }, "clear_pan_possible": { "type": "boolean", - "description": "indicates if retry with pan is possible" + "description": "indicates if retry with pan is possible\n**Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.", + "deprecated": true + }, + "feature": { + "$ref": "#/components/schemas/GsmFeature" + }, + "feature_data": { + "$ref": "#/components/schemas/GsmFeatureData" } } }, @@ -16253,7 +16301,8 @@ }, "step_up_possible": { "type": "boolean", - "description": "indicates if step_up retry is possible", + "description": "indicates if step_up retry is possible\n**Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.", + "deprecated": true, "nullable": true }, "unified_code": { @@ -16276,7 +16325,24 @@ }, "clear_pan_possible": { "type": "boolean", - "description": "indicates if retry with pan is possible", + "description": "indicates if retry with pan is possible\n**Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.", + "deprecated": true, + "nullable": true + }, + "feature": { + "allOf": [ + { + "$ref": "#/components/schemas/GsmFeature" + } + ], + "nullable": true + }, + "feature_data": { + "allOf": [ + { + "$ref": "#/components/schemas/GsmFeatureData" + } + ], "nullable": true } } @@ -29008,6 +29074,33 @@ "requeue" ] }, + "RetryFeatureData": { + "type": "object", + "description": "Represents the data associated with a retry feature in GSM.", + "required": [ + "step_up_possible", + "clear_pan_possible", + "alternate_network_possible", + "decision" + ], + "properties": { + "step_up_possible": { + "type": "boolean", + "description": "indicates if step_up retry is possible" + }, + "clear_pan_possible": { + "type": "boolean", + "description": "indicates if retry with pan is possible" + }, + "alternate_network_possible": { + "type": "boolean", + "description": "indicates if retry with alternate network possible" + }, + "decision": { + "$ref": "#/components/schemas/GsmDecision" + } + } + }, "RevokeApiKeyResponse": { "type": "object", "description": "The response body for revoking an API Key.", diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 3dcaf86d16d..8347355c128 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -12132,7 +12132,8 @@ }, "step_up_possible": { "type": "boolean", - "description": "indicates if step_up retry is possible" + "description": "indicates if step_up retry is possible\n**Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.", + "deprecated": true }, "unified_code": { "type": "string", @@ -12154,7 +12155,24 @@ }, "clear_pan_possible": { "type": "boolean", - "description": "indicates if retry with pan is possible" + "description": "indicates if retry with pan is possible\n**Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.", + "deprecated": true + }, + "feature": { + "allOf": [ + { + "$ref": "#/components/schemas/GsmFeature" + } + ], + "nullable": true + }, + "feature_data": { + "allOf": [ + { + "$ref": "#/components/schemas/GsmFeatureData" + } + ], + "nullable": true } } }, @@ -12162,7 +12180,6 @@ "type": "string", "enum": [ "retry", - "requeue", "do_default" ] }, @@ -12229,6 +12246,28 @@ } } }, + "GsmFeature": { + "type": "string", + "enum": [ + "retry" + ] + }, + "GsmFeatureData": { + "oneOf": [ + { + "type": "object", + "required": [ + "retry" + ], + "properties": { + "retry": { + "$ref": "#/components/schemas/RetryFeatureData" + } + } + } + ], + "description": "Contains the data relevant to the specified GSM feature, if applicable.\nFor example, if the `feature` is `Retry`, this will include configuration\ndetails specific to the retry behavior." + }, "GsmResponse": { "type": "object", "required": [ @@ -12240,7 +12279,9 @@ "status", "decision", "step_up_possible", - "clear_pan_possible" + "clear_pan_possible", + "feature", + "feature_data" ], "properties": { "connector": { @@ -12273,12 +12314,12 @@ "nullable": true }, "decision": { - "type": "string", - "description": "decision to be taken for auto retries flow" + "$ref": "#/components/schemas/GsmDecision" }, "step_up_possible": { "type": "boolean", - "description": "indicates if step_up retry is possible" + "description": "indicates if step_up retry is possible\n**Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.", + "deprecated": true }, "unified_code": { "type": "string", @@ -12300,7 +12341,14 @@ }, "clear_pan_possible": { "type": "boolean", - "description": "indicates if retry with pan is possible" + "description": "indicates if retry with pan is possible\n**Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.", + "deprecated": true + }, + "feature": { + "$ref": "#/components/schemas/GsmFeature" + }, + "feature_data": { + "$ref": "#/components/schemas/GsmFeatureData" } } }, @@ -12385,7 +12433,8 @@ }, "step_up_possible": { "type": "boolean", - "description": "indicates if step_up retry is possible", + "description": "indicates if step_up retry is possible\n**Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.", + "deprecated": true, "nullable": true }, "unified_code": { @@ -12408,7 +12457,24 @@ }, "clear_pan_possible": { "type": "boolean", - "description": "indicates if retry with pan is possible", + "description": "indicates if retry with pan is possible\n**Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant.", + "deprecated": true, + "nullable": true + }, + "feature": { + "allOf": [ + { + "$ref": "#/components/schemas/GsmFeature" + } + ], + "nullable": true + }, + "feature_data": { + "allOf": [ + { + "$ref": "#/components/schemas/GsmFeatureData" + } + ], "nullable": true } } @@ -22796,6 +22862,33 @@ "requeue" ] }, + "RetryFeatureData": { + "type": "object", + "description": "Represents the data associated with a retry feature in GSM.", + "required": [ + "step_up_possible", + "clear_pan_possible", + "alternate_network_possible", + "decision" + ], + "properties": { + "step_up_possible": { + "type": "boolean", + "description": "indicates if step_up retry is possible" + }, + "clear_pan_possible": { + "type": "boolean", + "description": "indicates if retry with pan is possible" + }, + "alternate_network_possible": { + "type": "boolean", + "description": "indicates if retry with alternate network possible" + }, + "decision": { + "$ref": "#/components/schemas/GsmDecision" + } + } + }, "RevenueRecoveryMetadata": { "type": "object", "description": "Revenue recovery metadata for merchant connector account", diff --git a/crates/api_models/src/gsm.rs b/crates/api_models/src/gsm.rs index 7ffc9c69413..1b2800d11ea 100644 --- a/crates/api_models/src/gsm.rs +++ b/crates/api_models/src/gsm.rs @@ -1,12 +1,12 @@ -use common_enums::ErrorCategory; use utoipa::ToSchema; -use crate::enums::Connector; +use crate::enums as api_enums; #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmCreateRequest { /// The connector through which payment has gone through - pub connector: Connector, + #[schema(value_type = Connector)] + pub connector: api_enums::Connector, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector @@ -20,23 +20,41 @@ pub struct GsmCreateRequest { /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow - pub decision: GsmDecision, + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] + #[schema(value_type = GsmDecision)] + pub decision: api_enums::GsmDecision, /// indicates if step_up retry is possible + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] pub step_up_possible: bool, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to - pub error_category: Option<ErrorCategory>, + #[schema(value_type = Option<ErrorCategory>)] + pub error_category: Option<api_enums::ErrorCategory>, /// indicates if retry with pan is possible + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] pub clear_pan_possible: bool, + /// Indicates the GSM feature associated with the request, + /// such as retry mechanisms or other specific functionalities provided by the system. + #[schema(value_type = Option<GsmFeature>)] + pub feature: Option<api_enums::GsmFeature>, + /// Contains the data relevant to the specified GSM feature, if applicable. + /// For example, if the `feature` is `Retry`, this will include configuration + /// details specific to the retry behavior. + #[schema(value_type = Option<GsmFeatureData>)] + pub feature_data: Option<common_types::domain::GsmFeatureData>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmRetrieveRequest { /// The connector through which payment has gone through - pub connector: Connector, + #[schema(value_type = Connector)] + pub connector: api_enums::Connector, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector @@ -47,28 +65,6 @@ pub struct GsmRetrieveRequest { pub message: String, } -#[derive( - Default, - Clone, - Copy, - Debug, - strum::Display, - PartialEq, - Eq, - serde::Serialize, - serde::Deserialize, - strum::EnumString, - ToSchema, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum GsmDecision { - Retry, - Requeue, - #[default] - DoDefault, -} - #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmUpdateRequest { /// The connector through which payment has gone through @@ -86,17 +82,34 @@ pub struct GsmUpdateRequest { /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow - pub decision: Option<GsmDecision>, + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] + #[schema(value_type = Option<GsmDecision>)] + pub decision: Option<api_enums::GsmDecision>, /// indicates if step_up retry is possible + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] pub step_up_possible: Option<bool>, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to - pub error_category: Option<ErrorCategory>, + #[schema(value_type = Option<ErrorCategory>)] + pub error_category: Option<api_enums::ErrorCategory>, /// indicates if retry with pan is possible + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] pub clear_pan_possible: Option<bool>, + /// Indicates the GSM feature associated with the request, + /// such as retry mechanisms or other specific functionalities provided by the system. + #[schema(value_type = Option<GsmFeature>)] + pub feature: Option<api_enums::GsmFeature>, + /// Contains the data relevant to the specified GSM feature, if applicable. + /// For example, if the `feature` is `Retry`, this will include configuration + /// details specific to the retry behavior. + #[schema(value_type = Option<GsmFeatureData>)] + pub feature_data: Option<common_types::domain::GsmFeatureData>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -143,15 +156,32 @@ pub struct GsmResponse { /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow - pub decision: String, + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] + #[schema(value_type = GsmDecision)] + pub decision: api_enums::GsmDecision, /// indicates if step_up retry is possible + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] pub step_up_possible: bool, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to - pub error_category: Option<ErrorCategory>, + #[schema(value_type = Option<ErrorCategory>)] + pub error_category: Option<api_enums::ErrorCategory>, /// indicates if retry with pan is possible + /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. + #[schema(deprecated)] pub clear_pan_possible: bool, + /// Indicates the GSM feature associated with the request, + /// such as retry mechanisms or other specific functionalities provided by the system. + #[schema(value_type = GsmFeature)] + pub feature: api_enums::GsmFeature, + /// Contains the data relevant to the specified GSM feature, if applicable. + /// For example, if the `feature` is `Retry`, this will include configuration + /// details specific to the retry behavior. + #[schema(value_type = GsmFeatureData)] + pub feature_data: Option<common_types::domain::GsmFeatureData>, } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 4daa373c016..6b35bbaf9ce 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -267,6 +267,46 @@ pub enum RevenueRecoveryAlgorithmType { Cascading, } +#[derive( + Default, + Clone, + Copy, + Debug, + strum::Display, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::EnumString, + ToSchema, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum GsmDecision { + Retry, + #[default] + DoDefault, +} + +#[derive( + Clone, + Copy, + Debug, + strum::Display, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::EnumString, + ToSchema, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +#[router_derive::diesel_enum(storage_type = "text")] +pub enum GsmFeature { + Retry, +} + /// Specifies the type of cardholder authentication to be applied for a payment. /// /// - `ThreeDs`: Requests 3D Secure (3DS) authentication. If the card is enrolled, 3DS authentication will be activated, potentially shifting chargeback liability to the issuer. diff --git a/crates/common_types/src/domain.rs b/crates/common_types/src/domain.rs index e800cb9cb61..3836aaabe75 100644 --- a/crates/common_types/src/domain.rs +++ b/crates/common_types/src/domain.rs @@ -113,3 +113,71 @@ pub struct ConnectorResponseData { /// Stringified connector raw response body pub raw_connector_response: Option<Secret<String>>, } + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, AsExpression, ToSchema)] +#[diesel(sql_type = Jsonb)] +#[serde(rename_all = "snake_case")] +/// Contains the data relevant to the specified GSM feature, if applicable. +/// For example, if the `feature` is `Retry`, this will include configuration +/// details specific to the retry behavior. +pub enum GsmFeatureData { + /// Represents the data associated with a retry feature in GSM. + Retry(RetryFeatureData), +} + +/// Represents the data associated with a retry feature in GSM. +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, AsExpression, ToSchema)] +#[diesel(sql_type = Jsonb)] +pub struct RetryFeatureData { + /// indicates if step_up retry is possible + pub step_up_possible: bool, + /// indicates if retry with pan is possible + pub clear_pan_possible: bool, + /// indicates if retry with alternate network possible + pub alternate_network_possible: bool, + /// decision to be taken for auto retries flow + #[schema(value_type = GsmDecision)] + pub decision: common_enums::GsmDecision, +} + +impl_to_sql_from_sql_json!(GsmFeatureData); +impl_to_sql_from_sql_json!(RetryFeatureData); + +impl GsmFeatureData { + /// Retrieves the retry feature data if it exists. + pub fn get_retry_feature_data(&self) -> Option<RetryFeatureData> { + match self { + Self::Retry(data) => Some(data.clone()), + } + } + + /// Retrieves the decision from the retry feature data. + pub fn get_decision(&self) -> common_enums::GsmDecision { + match self { + Self::Retry(data) => data.decision, + } + } +} + +/// Implementation of methods for `RetryFeatureData` +impl RetryFeatureData { + /// Checks if step-up retry is possible. + pub fn is_step_up_possible(&self) -> bool { + self.step_up_possible + } + + /// Checks if retry with PAN is possible. + pub fn is_clear_pan_possible(&self) -> bool { + self.clear_pan_possible + } + + /// Checks if retry with alternate network is possible. + pub fn is_alternate_network_possible(&self) -> bool { + self.alternate_network_possible + } + + /// Retrieves the decision to be taken for auto retries flow. + pub fn get_decision(&self) -> common_enums::GsmDecision { + self.decision + } +} diff --git a/crates/diesel_models/src/gsm.rs b/crates/diesel_models/src/gsm.rs index 46583a5b22c..b75b0e6ce86 100644 --- a/crates/diesel_models/src/gsm.rs +++ b/crates/diesel_models/src/gsm.rs @@ -1,5 +1,4 @@ //! Gateway status mapping - use common_enums::ErrorCategory; use common_utils::{ custom_serde, @@ -15,8 +14,6 @@ use crate::schema::gateway_status_map; Debug, Eq, PartialEq, - Ord, - PartialOrd, router_derive::DebugAsDisplay, Identifiable, Queryable, @@ -42,6 +39,8 @@ pub struct GatewayStatusMap { pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub clear_pan_possible: bool, + pub feature_data: Option<common_types::domain::GsmFeatureData>, + pub feature: Option<common_enums::GsmFeature>, } #[derive(Clone, Debug, Eq, PartialEq, Insertable)] @@ -60,6 +59,8 @@ pub struct GatewayStatusMappingNew { pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub clear_pan_possible: bool, + pub feature_data: Option<common_types::domain::GsmFeatureData>, + pub feature: Option<common_enums::GsmFeature>, } #[derive( @@ -81,6 +82,8 @@ pub struct GatewayStatusMapperUpdateInternal { pub error_category: Option<ErrorCategory>, pub last_modified: PrimitiveDateTime, pub clear_pan_possible: Option<bool>, + pub feature_data: Option<common_types::domain::GsmFeatureData>, + pub feature: Option<common_enums::GsmFeature>, } #[derive(Debug)] @@ -93,6 +96,8 @@ pub struct GatewayStatusMappingUpdate { pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub clear_pan_possible: Option<bool>, + pub feature_data: Option<common_types::domain::GsmFeatureData>, + pub feature: Option<common_enums::GsmFeature>, } impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { @@ -106,6 +111,8 @@ impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { unified_message, error_category, clear_pan_possible, + feature_data, + feature, } = value; Self { status, @@ -122,6 +129,8 @@ impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { code: None, message: None, clear_pan_possible, + feature_data, + feature, } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 6788f478274..c141f765536 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -595,6 +595,9 @@ diesel::table! { #[max_length = 64] error_category -> Nullable<Varchar>, clear_pan_possible -> Bool, + feature_data -> Nullable<Jsonb>, + #[max_length = 64] + feature -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index c5579b6c67b..e434e43b2c6 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -607,6 +607,9 @@ diesel::table! { #[max_length = 64] error_category -> Nullable<Varchar>, clear_pan_possible -> Bool, + feature_data -> Nullable<Jsonb>, + #[max_length = 64] + feature -> Nullable<Varchar>, } } diff --git a/crates/hyperswitch_domain_models/src/gsm.rs b/crates/hyperswitch_domain_models/src/gsm.rs new file mode 100644 index 00000000000..59319c89e5d --- /dev/null +++ b/crates/hyperswitch_domain_models/src/gsm.rs @@ -0,0 +1,129 @@ +use common_utils::{errors::ValidationError, ext_traits::StringExt}; +use serde::{self, Deserialize, Serialize}; + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +pub struct GatewayStatusMap { + pub connector: String, + pub flow: String, + pub sub_flow: String, + pub code: String, + pub message: String, + pub status: String, + pub router_error: Option<String>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, + pub error_category: Option<common_enums::ErrorCategory>, + pub feature_data: common_types::domain::GsmFeatureData, + pub feature: common_enums::GsmFeature, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct GatewayStatusMappingUpdate { + pub status: Option<String>, + pub router_error: Option<Option<String>>, + pub decision: Option<common_enums::GsmDecision>, + pub step_up_possible: Option<bool>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, + pub error_category: Option<common_enums::ErrorCategory>, + pub clear_pan_possible: Option<bool>, + pub feature_data: Option<common_types::domain::GsmFeatureData>, + pub feature: Option<common_enums::GsmFeature>, +} + +impl TryFrom<GatewayStatusMap> for diesel_models::gsm::GatewayStatusMappingNew { + type Error = error_stack::Report<ValidationError>; + + fn try_from(value: GatewayStatusMap) -> Result<Self, Self::Error> { + Ok(Self { + connector: value.connector.to_string(), + flow: value.flow, + sub_flow: value.sub_flow, + code: value.code, + message: value.message, + status: value.status.clone(), + router_error: value.router_error, + decision: value.feature_data.get_decision().to_string(), + step_up_possible: value + .feature_data + .get_retry_feature_data() + .map(|retry_feature_data| retry_feature_data.is_step_up_possible()) + .unwrap_or(false), + unified_code: value.unified_code, + unified_message: value.unified_message, + error_category: value.error_category, + clear_pan_possible: value + .feature_data + .get_retry_feature_data() + .map(|retry_feature_data| retry_feature_data.is_clear_pan_possible()) + .unwrap_or(false), + feature_data: Some(value.feature_data), + feature: Some(value.feature), + }) + } +} + +impl TryFrom<GatewayStatusMappingUpdate> for diesel_models::gsm::GatewayStatusMappingUpdate { + type Error = error_stack::Report<ValidationError>; + + fn try_from(value: GatewayStatusMappingUpdate) -> Result<Self, Self::Error> { + Ok(Self { + status: value.status, + router_error: value.router_error, + decision: value.decision.map(|gsm_decision| gsm_decision.to_string()), + step_up_possible: value.step_up_possible, + unified_code: value.unified_code, + unified_message: value.unified_message, + error_category: value.error_category, + clear_pan_possible: value.clear_pan_possible, + feature_data: value.feature_data, + feature: value.feature, + }) + } +} + +impl TryFrom<diesel_models::gsm::GatewayStatusMap> for GatewayStatusMap { + type Error = ValidationError; + + fn try_from(item: diesel_models::gsm::GatewayStatusMap) -> Result<Self, Self::Error> { + let decision = + StringExt::<common_enums::GsmDecision>::parse_enum(item.decision, "GsmDecision") + .map_err(|_| ValidationError::InvalidValue { + message: "Failed to parse GsmDecision".to_string(), + })?; + let db_feature_data = item.feature_data; + + // The only case where `FeatureData` can be null is for legacy records + // (i.e., records created before `FeatureData` and related features were introduced). + // At that time, the only supported feature was `Retry`, so it's safe to default to it. + let feature_data = match db_feature_data { + Some(common_types::domain::GsmFeatureData::Retry(data)) => { + common_types::domain::GsmFeatureData::Retry(data) + } + None => common_types::domain::GsmFeatureData::Retry( + common_types::domain::RetryFeatureData { + step_up_possible: item.step_up_possible, + clear_pan_possible: item.clear_pan_possible, + alternate_network_possible: false, + decision, + }, + ), + }; + + let feature = item.feature.unwrap_or(common_enums::GsmFeature::Retry); + Ok(Self { + connector: item.connector, + flow: item.flow, + sub_flow: item.sub_flow, + code: item.code, + message: item.message, + status: item.status, + router_error: item.router_error, + unified_code: item.unified_code, + unified_message: item.unified_message, + error_category: item.error_category, + feature_data, + feature, + }) + } +} diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index c7df1e3749b..30d0913a716 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -14,6 +14,7 @@ pub mod customer; pub mod disputes; pub mod errors; pub mod ext_traits; +pub mod gsm; pub mod mandates; pub mod merchant_account; pub mod merchant_connector_account; diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index efa92af978a..bb2937a653e 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -400,7 +400,10 @@ Never share your secret api keys. Keep them guarded and secure. api_models::gsm::GsmDeleteRequest, api_models::gsm::GsmDeleteResponse, api_models::gsm::GsmResponse, - api_models::gsm::GsmDecision, + api_models::enums::GsmDecision, + api_models::enums::GsmFeature, + common_types::domain::GsmFeatureData, + common_types::domain::RetryFeatureData, api_models::payments::AddressDetails, api_models::payments::BankDebitData, api_models::payments::AliPayQr, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 81e8f10dcdc..23f0fa2d0d2 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -352,7 +352,10 @@ Never share your secret api keys. Keep them guarded and secure. api_models::gsm::GsmDeleteRequest, api_models::gsm::GsmDeleteResponse, api_models::gsm::GsmResponse, - api_models::gsm::GsmDecision, + api_models::enums::GsmDecision, + api_models::enums::GsmFeature, + common_types::domain::GsmFeatureData, + common_types::domain::RetryFeatureData, api_models::payments::NullObject, api_models::payments::AddressDetails, api_models::payments::BankDebitData, diff --git a/crates/router/src/core/gsm.rs b/crates/router/src/core/gsm.rs index 6c544791a18..4bd93a4e0e0 100644 --- a/crates/router/src/core/gsm.rs +++ b/crates/router/src/core/gsm.rs @@ -1,16 +1,12 @@ use api_models::gsm as gsm_api_types; -use diesel_models::gsm as storage; use error_stack::ResultExt; use router_env::{instrument, tracing}; use crate::{ - core::{ - errors, - errors::{RouterResponse, StorageErrorExt}, - }, + core::errors::{self, RouterResponse, StorageErrorExt}, db::gsm::GsmInterface, services, - types::transformers::ForeignInto, + types::transformers::{ForeignFrom, ForeignInto}, SessionState, }; @@ -55,6 +51,24 @@ pub async fn update_gsm_rule( gsm_request: gsm_api_types::GsmUpdateRequest, ) -> RouterResponse<gsm_api_types::GsmResponse> { let db = state.store.as_ref(); + let connector = gsm_request.connector.clone(); + let flow = gsm_request.flow.clone(); + let code = gsm_request.code.clone(); + let sub_flow = gsm_request.sub_flow.clone(); + let message = gsm_request.message.clone(); + + let gsm_db_record = + GsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "GSM with given key does not exist in our records".to_string(), + })?; + + let inferred_feature_info = <( + common_enums::GsmFeature, + common_types::domain::GsmFeatureData, + )>::foreign_from((&gsm_request, gsm_db_record)); + let gsm_api_types::GsmUpdateRequest { connector, flow, @@ -69,6 +83,8 @@ pub async fn update_gsm_rule( unified_message, error_category, clear_pan_possible, + feature, + feature_data, } = gsm_request; GsmInterface::update_gsm_rule( db, @@ -77,15 +93,25 @@ pub async fn update_gsm_rule( sub_flow, code, message, - storage::GatewayStatusMappingUpdate { - decision: decision.map(|d| d.to_string()), + hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate { + decision, status, router_error: Some(router_error), - step_up_possible, + step_up_possible: feature_data + .as_ref() + .and_then(|feature_data| feature_data.get_retry_feature_data()) + .map(|retry_feature_data| retry_feature_data.is_step_up_possible()) + .or(step_up_possible), unified_code, unified_message, error_category, - clear_pan_possible, + clear_pan_possible: feature_data + .as_ref() + .and_then(|feature_data| feature_data.get_retry_feature_data()) + .map(|retry_feature_data| retry_feature_data.is_clear_pan_possible()) + .or(clear_pan_possible), + feature_data: feature_data.or(Some(inferred_feature_info.1)), + feature: feature.or(Some(inferred_feature_info.0)), }, ) .await diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 458fe4bc5b2..ca8a9708651 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -6441,7 +6441,7 @@ pub async fn get_gsm_record( error_message: Option<String>, connector_name: String, flow: String, -) -> Option<storage::gsm::GatewayStatusMap> { +) -> Option<hyperswitch_domain_models::gsm::GatewayStatusMap> { let get_gsm = || async { state.store.find_gsm_rule( connector_name.clone(), diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index aafe25aea67..b435bd191ef 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -1,8 +1,8 @@ -use std::{str::FromStr, vec::IntoIter}; +use std::vec::IntoIter; use common_utils::{ext_traits::Encode, types::MinorUnit}; use diesel_models::enums as storage_enums; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use router_env::{ logger, tracing::{self, instrument}, @@ -65,10 +65,10 @@ where let mut initial_gsm = get_gsm(state, &router_data).await?; - //Check if step-up to threeDS is possible and merchant has enabled let step_up_possible = initial_gsm - .clone() - .map(|gsm| gsm.step_up_possible) + .as_ref() + .and_then(|data| data.feature_data.get_retry_feature_data()) + .map(|data| data.is_step_up_possible()) .unwrap_or(false); #[cfg(feature = "v1")] @@ -124,7 +124,7 @@ where }; match get_gsm_decision(gsm) { - api_models::gsm::GsmDecision::Retry => { + storage_enums::GsmDecision::Retry => { retries = get_retries( state, retries, @@ -150,11 +150,13 @@ where .map(|pmd| pmd.is_network_token_payment_method_data()) .unwrap_or(false); + let clear_pan_possible = initial_gsm + .and_then(|data| data.feature_data.get_retry_feature_data()) + .map(|data| data.is_clear_pan_possible()) + .unwrap_or(false); + let should_retry_with_pan = is_network_token - && initial_gsm - .as_ref() - .map(|gsm| gsm.clear_pan_possible) - .unwrap_or(false) + && clear_pan_possible && business_profile.is_clear_pan_retries_enabled; let (connector, routing_decision) = if should_retry_with_pan { @@ -195,14 +197,7 @@ where retries = retries.map(|i| i - 1); } - api_models::gsm::GsmDecision::Requeue => { - Err(report!(errors::ApiErrorResponse::NotImplemented { - message: errors::NotImplementedMessage::Reason( - "Requeue not implemented".to_string(), - ), - }))? - } - api_models::gsm::GsmDecision::DoDefault => break, + storage_enums::GsmDecision::DoDefault => break, } initial_gsm = None; } @@ -278,7 +273,7 @@ pub async fn get_retries( pub async fn get_gsm<F, FData>( state: &app::SessionState, router_data: &types::RouterData<F, FData, types::PaymentsResponseData>, -) -> RouterResult<Option<storage::gsm::GatewayStatusMap>> { +) -> RouterResult<Option<hyperswitch_domain_models::gsm::GatewayStatusMap>> { let error_response = router_data.response.as_ref().err(); let error_code = error_response.map(|err| err.code.to_owned()); let error_message = error_response.map(|err| err.message.to_owned()); @@ -292,19 +287,11 @@ pub async fn get_gsm<F, FData>( #[instrument(skip_all)] pub fn get_gsm_decision( - option_gsm: Option<storage::gsm::GatewayStatusMap>, -) -> api_models::gsm::GsmDecision { + option_gsm: Option<hyperswitch_domain_models::gsm::GatewayStatusMap>, +) -> storage_enums::GsmDecision { let option_gsm_decision = option_gsm - .and_then(|gsm| { - api_models::gsm::GsmDecision::from_str(gsm.decision.as_str()) - .map_err(|err| { - let api_error = report!(err).change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("gsm decision parsing failed"); - logger::warn!(get_gsm_decision_parse_error=?api_error, "error fetching gsm decision"); - api_error - }) - .ok() - }); + .as_ref() + .map(|gsm| gsm.feature_data.get_decision()); if option_gsm_decision.is_some() { metrics::AUTO_RETRY_GSM_MATCH_COUNT.add(1, &[]); diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index f1f8dad3a05..8a7f87fa60d 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1060,7 +1060,7 @@ pub async fn get_gsm_record( error_message: Option<String>, connector_name: Option<String>, flow: &str, -) -> Option<storage::gsm::GatewayStatusMap> { +) -> Option<hyperswitch_domain_models::gsm::GatewayStatusMap> { let connector_name = connector_name.unwrap_or_default(); let get_gsm = || async { state.store.find_gsm_rule( diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs index 30100a580d4..e4579613605 100644 --- a/crates/router/src/core/payouts/retry.rs +++ b/crates/router/src/core/payouts/retry.rs @@ -1,7 +1,7 @@ -use std::{cmp::Ordering, str::FromStr, vec::IntoIter}; +use std::vec::IntoIter; use common_enums::PayoutRetryType; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use router_env::{ logger, tracing::{self, instrument}, @@ -38,7 +38,7 @@ pub async fn do_gsm_multiple_connector_actions( let gsm = get_gsm(state, &connector, payout_data).await?; match get_gsm_decision(gsm) { - api_models::gsm::GsmDecision::Retry => { + common_enums::GsmDecision::Retry => { retries = get_retries( state, retries, @@ -71,14 +71,7 @@ pub async fn do_gsm_multiple_connector_actions( retries = retries.map(|i| i - 1); } - api_models::gsm::GsmDecision::Requeue => { - Err(report!(errors::ApiErrorResponse::NotImplemented { - message: errors::NotImplementedMessage::Reason( - "Requeue not implemented".to_string(), - ), - }))? - } - api_models::gsm::GsmDecision::DoDefault => break, + common_enums::GsmDecision::DoDefault => break, } } Ok(()) @@ -102,13 +95,13 @@ pub async fn do_gsm_single_connector_actions( let gsm = get_gsm(state, &original_connector_data, payout_data).await?; // if the error config is same as previous, we break out of the loop - if let Ordering::Equal = gsm.cmp(&previous_gsm) { + if gsm == previous_gsm { break; } previous_gsm.clone_from(&gsm); match get_gsm_decision(gsm) { - api_models::gsm::GsmDecision::Retry => { + common_enums::GsmDecision::Retry => { retries = get_retries( state, retries, @@ -133,14 +126,7 @@ pub async fn do_gsm_single_connector_actions( retries = retries.map(|i| i - 1); } - api_models::gsm::GsmDecision::Requeue => { - Err(report!(errors::ApiErrorResponse::NotImplemented { - message: errors::NotImplementedMessage::Reason( - "Requeue not implemented".to_string(), - ), - }))? - } - api_models::gsm::GsmDecision::DoDefault => break, + common_enums::GsmDecision::DoDefault => break, } } Ok(()) @@ -182,7 +168,7 @@ pub async fn get_gsm( state: &app::SessionState, original_connector_data: &api::ConnectorData, payout_data: &PayoutData, -) -> RouterResult<Option<storage::gsm::GatewayStatusMap>> { +) -> RouterResult<Option<hyperswitch_domain_models::gsm::GatewayStatusMap>> { let error_code = payout_data.payout_attempt.error_code.to_owned(); let error_message = payout_data.payout_attempt.error_message.to_owned(); let connector_name = Some(original_connector_data.connector_name.to_string()); @@ -199,19 +185,9 @@ pub async fn get_gsm( #[instrument(skip_all)] pub fn get_gsm_decision( - option_gsm: Option<storage::gsm::GatewayStatusMap>, -) -> api_models::gsm::GsmDecision { - let option_gsm_decision = option_gsm - .and_then(|gsm| { - api_models::gsm::GsmDecision::from_str(gsm.decision.as_str()) - .map_err(|err| { - let api_error = report!(err).change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("gsm decision parsing failed"); - logger::warn!(get_gsm_decision_parse_error=?api_error, "error fetching gsm decision"); - api_error - }) - .ok() - }); + option_gsm: Option<hyperswitch_domain_models::gsm::GatewayStatusMap>, +) -> common_enums::GsmDecision { + let option_gsm_decision = option_gsm.map(|gsm| gsm.feature_data.get_decision()); if option_gsm_decision.is_some() { metrics::AUTO_PAYOUT_RETRY_GSM_MATCH_COUNT.add(1, &[]); diff --git a/crates/router/src/db/gsm.rs b/crates/router/src/db/gsm.rs index 1aa96e14c18..eb88eecd4c4 100644 --- a/crates/router/src/db/gsm.rs +++ b/crates/router/src/db/gsm.rs @@ -1,5 +1,5 @@ use diesel_models::gsm as storage; -use error_stack::report; +use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::MockDb; @@ -13,8 +13,8 @@ use crate::{ pub trait GsmInterface { async fn add_gsm_rule( &self, - rule: storage::GatewayStatusMappingNew, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError>; + rule: hyperswitch_domain_models::gsm::GatewayStatusMap, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError>; async fn find_gsm_decision( &self, connector: String, @@ -30,7 +30,7 @@ pub trait GsmInterface { sub_flow: String, code: String, message: String, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError>; + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError>; async fn update_gsm_rule( &self, connector: String, @@ -38,8 +38,8 @@ pub trait GsmInterface { sub_flow: String, code: String, message: String, - data: storage::GatewayStatusMappingUpdate, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError>; + data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError>; async fn delete_gsm_rule( &self, @@ -56,12 +56,19 @@ impl GsmInterface for Store { #[instrument(skip_all)] async fn add_gsm_rule( &self, - rule: storage::GatewayStatusMappingNew, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + rule: hyperswitch_domain_models::gsm::GatewayStatusMap, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - rule.insert(&conn) + let gsm_db_record = diesel_models::gsm::GatewayStatusMappingNew::try_from(rule) + .change_context(errors::StorageError::SerializationFailed) + .attach_printable("Failed to convert gsm domain models to diesel models")? + .insert(&conn) .await - .map_err(|error| report!(errors::StorageError::from(error))) + .map_err(|error| report!(errors::StorageError::from(error)))?; + + hyperswitch_domain_models::gsm::GatewayStatusMap::try_from(gsm_db_record) + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Failed to convert gsm diesel models to domain models") } #[instrument(skip_all)] @@ -89,11 +96,16 @@ impl GsmInterface for Store { sub_flow: String, code: String, message: String, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::GatewayStatusMap::find(&conn, connector, flow, sub_flow, code, message) - .await - .map_err(|error| report!(errors::StorageError::from(error))) + let gsm_db_record = + storage::GatewayStatusMap::find(&conn, connector, flow, sub_flow, code, message) + .await + .map_err(|error| report!(errors::StorageError::from(error)))?; + + hyperswitch_domain_models::gsm::GatewayStatusMap::try_from(gsm_db_record) + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Failed to convert gsm diesel models to domain models") } #[instrument(skip_all)] @@ -104,12 +116,26 @@ impl GsmInterface for Store { sub_flow: String, code: String, message: String, - data: storage::GatewayStatusMappingUpdate, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::GatewayStatusMap::update(&conn, connector, flow, sub_flow, code, message, data) - .await - .map_err(|error| report!(errors::StorageError::from(error))) + let gsm_update_data = diesel_models::gsm::GatewayStatusMappingUpdate::try_from(data) + .change_context(errors::StorageError::SerializationFailed)?; + let gsm_db_record = storage::GatewayStatusMap::update( + &conn, + connector, + flow, + sub_flow, + code, + message, + gsm_update_data, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error)))?; + + hyperswitch_domain_models::gsm::GatewayStatusMap::try_from(gsm_db_record) + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Failed to convert gsm diesel models to domain models") } #[instrument(skip_all)] @@ -132,8 +158,8 @@ impl GsmInterface for Store { impl GsmInterface for MockDb { async fn add_gsm_rule( &self, - _rule: storage::GatewayStatusMappingNew, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + _rule: hyperswitch_domain_models::gsm::GatewayStatusMap, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } @@ -155,7 +181,7 @@ impl GsmInterface for MockDb { _sub_flow: String, _code: String, _message: String, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } @@ -166,8 +192,8 @@ impl GsmInterface for MockDb { _sub_flow: String, _code: String, _message: String, - _data: storage::GatewayStatusMappingUpdate, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + _data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index b81e5c1f71c..412cc0a4a10 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3185,8 +3185,8 @@ impl RoutingAlgorithmInterface for KafkaStore { impl GsmInterface for KafkaStore { async fn add_gsm_rule( &self, - rule: storage::GatewayStatusMappingNew, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + rule: hyperswitch_domain_models::gsm::GatewayStatusMap, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { self.diesel_store.add_gsm_rule(rule).await } @@ -3210,7 +3210,7 @@ impl GsmInterface for KafkaStore { sub_flow: String, code: String, message: String, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { self.diesel_store .find_gsm_rule(connector, flow, sub_flow, code, message) .await @@ -3223,8 +3223,8 @@ impl GsmInterface for KafkaStore { sub_flow: String, code: String, message: String, - data: storage::GatewayStatusMappingUpdate, - ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { + data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate, + ) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> { self.diesel_store .update_gsm_rule(connector, flow, sub_flow, code, message, data) .await diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 7b38342a743..90f2a423595 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1586,42 +1586,129 @@ impl ForeignFrom<api_models::organization::OrganizationCreateRequest> } } -impl ForeignFrom<gsm_api_types::GsmCreateRequest> for storage::GatewayStatusMappingNew { +impl ForeignFrom<gsm_api_types::GsmCreateRequest> + for hyperswitch_domain_models::gsm::GatewayStatusMap +{ fn foreign_from(value: gsm_api_types::GsmCreateRequest) -> Self { + let inferred_feature_data = common_types::domain::GsmFeatureData::foreign_from(&value); Self { connector: value.connector.to_string(), flow: value.flow, sub_flow: value.sub_flow, code: value.code, message: value.message, - decision: value.decision.to_string(), status: value.status, router_error: value.router_error, - step_up_possible: value.step_up_possible, unified_code: value.unified_code, unified_message: value.unified_message, error_category: value.error_category, - clear_pan_possible: value.clear_pan_possible, + feature_data: value.feature_data.unwrap_or(inferred_feature_data), + feature: value.feature.unwrap_or(api_enums::GsmFeature::Retry), + } + } +} + +impl ForeignFrom<&gsm_api_types::GsmCreateRequest> for common_types::domain::GsmFeatureData { + fn foreign_from(value: &gsm_api_types::GsmCreateRequest) -> Self { + // Defaulting alternate_network_possible to false as it is provided only in the Retry feature + // If the retry feature is not used, we assume alternate network as false + let alternate_network_possible = false; + + match value.feature { + Some(api_enums::GsmFeature::Retry) | None => { + Self::Retry(common_types::domain::RetryFeatureData { + step_up_possible: value.step_up_possible, + clear_pan_possible: value.clear_pan_possible, + alternate_network_possible, + decision: value.decision, + }) + } + } + } +} + +impl + ForeignFrom<( + &gsm_api_types::GsmUpdateRequest, + hyperswitch_domain_models::gsm::GatewayStatusMap, + )> for (api_enums::GsmFeature, common_types::domain::GsmFeatureData) +{ + fn foreign_from( + (gsm_update_request, gsm_db_record): ( + &gsm_api_types::GsmUpdateRequest, + hyperswitch_domain_models::gsm::GatewayStatusMap, + ), + ) -> Self { + let gsm_db_record_infered_feature = match gsm_db_record.feature_data.get_decision() { + api_enums::GsmDecision::Retry | api_enums::GsmDecision::DoDefault => { + api_enums::GsmFeature::Retry + } + }; + + let gsm_feature = gsm_update_request + .feature + .unwrap_or(gsm_db_record_infered_feature); + + match gsm_feature { + api_enums::GsmFeature::Retry => { + let gsm_db_record_retry_feature_data = + gsm_db_record.feature_data.get_retry_feature_data(); + + let retry_feature_data = common_types::domain::GsmFeatureData::Retry( + common_types::domain::RetryFeatureData { + step_up_possible: gsm_update_request + .step_up_possible + .or(gsm_db_record_retry_feature_data + .clone() + .map(|data| data.step_up_possible)) + .unwrap_or_default(), + clear_pan_possible: gsm_update_request + .clear_pan_possible + .or(gsm_db_record_retry_feature_data + .clone() + .map(|data| data.clear_pan_possible)) + .unwrap_or_default(), + alternate_network_possible: gsm_db_record_retry_feature_data + .map(|data| data.alternate_network_possible) + .unwrap_or_default(), + decision: gsm_update_request + .decision + .or(Some(gsm_db_record.feature_data.get_decision())) + .unwrap_or_default(), + }, + ); + (api_enums::GsmFeature::Retry, retry_feature_data) + } } } } -impl ForeignFrom<storage::GatewayStatusMap> for gsm_api_types::GsmResponse { - fn foreign_from(value: storage::GatewayStatusMap) -> Self { +impl ForeignFrom<hyperswitch_domain_models::gsm::GatewayStatusMap> for gsm_api_types::GsmResponse { + fn foreign_from(value: hyperswitch_domain_models::gsm::GatewayStatusMap) -> Self { Self { connector: value.connector.to_string(), flow: value.flow, sub_flow: value.sub_flow, code: value.code, message: value.message, - decision: value.decision.to_string(), + decision: value.feature_data.get_decision(), status: value.status, router_error: value.router_error, - step_up_possible: value.step_up_possible, + step_up_possible: value + .feature_data + .get_retry_feature_data() + .map(|data| data.is_step_up_possible()) + .unwrap_or(false), unified_code: value.unified_code, unified_message: value.unified_message, error_category: value.error_category, - clear_pan_possible: value.clear_pan_possible, + clear_pan_possible: value + .feature_data + .get_retry_feature_data() + .map(|data| data.is_clear_pan_possible()) + .unwrap_or(false), + feature_data: Some(value.feature_data), + feature: value.feature, } } } diff --git a/migrations/2025-04-07-133030_add_feature_data_column_to_gsm/down.sql b/migrations/2025-04-07-133030_add_feature_data_column_to_gsm/down.sql new file mode 100644 index 00000000000..35bcb7d37f1 --- /dev/null +++ b/migrations/2025-04-07-133030_add_feature_data_column_to_gsm/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE gateway_status_map DROP COLUMN IF EXISTS feature_data, + DROP COLUMN IF EXISTS feature; \ No newline at end of file diff --git a/migrations/2025-04-07-133030_add_feature_data_column_to_gsm/up.sql b/migrations/2025-04-07-133030_add_feature_data_column_to_gsm/up.sql new file mode 100644 index 00000000000..1e53a532e8b --- /dev/null +++ b/migrations/2025-04-07-133030_add_feature_data_column_to_gsm/up.sql @@ -0,0 +1,4 @@ +-- Your SQL goes here +ALTER TABLE gateway_status_map +ADD COLUMN IF NOT EXISTS feature_data JSONB DEFAULT NULL, + ADD COLUMN IF NOT EXISTS feature VARCHAR(64) DEFAULT NULL; \ No newline at end of file
2025-04-09T05:17:41Z
## 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 includes a number of changes to the `gsm` module across multiple files to introduce new features and improve the existing code structure. The most important changes include the addition of new fields and enums, refactoring of existing enums, and introducing domain models for gsm. ### Changes to `gsm` module: * `crates/api_models/src/gsm.rs`: * Added new fields `alternate_network_possible` and `feature` to `GsmCreateRequest`, `GsmUpdateRequest`, and `GsmResponse` structs. * `step_up_possible` and `clear_pan_possible` are made as optional in api contract these are retry feature specific data and might not be present for other features. * `crates/common_enums/src/enums.rs`: * Added new enum`GsmFeature` to handle GSM decision and feature data. * Remove `Requeue` as feature us not yet implemented ### 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 gsm rule without passing feature and feature data ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "adyenplatform", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "retry", "step_up_possible": true, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true, "alternate_network_possible": false }' ``` ``` { "connector": "adyenplatform", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "retry", "step_up_possible": true, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true, "feature": "retry", "feature_data": { "retry": { "step_up_possible": true, "clear_pan_possible": true, "alternate_network_possible": false, "decision": "retry" } } } ``` ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true }' ``` ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true }' ``` Db entry <img width="2334" height="239" alt="image" src="https://github.com/user-attachments/assets/fd177675-dd2f-41d5-abf4-3b6c28411cda" /> ### Update rule `"clear_pan_possible": false` ``` curl --location 'http://localhost:8080/gsm/update' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": false }' ``` ``` { "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": false, "feature": "retry", "feature_data": { "retry": { "step_up_possible": false, "clear_pan_possible": false, "alternate_network_possible": false, "decision": "do_default" } } } ``` ### Test case of existing records (manually create db entries like the existing ones and try to update it) db entry showing feature and feature_data to be null <img width="1310" height="312" alt="image" src="https://github.com/user-attachments/assets/8a1af508-2899-4c56-a112-af37363542c5" /> -> update call will `"clear_pan_possible": true` ``` curl --location 'http://localhost:8080/gsm/update' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "novalnet", "flow": "Authorize", "sub_flow": "sub_flow", "code": "525002", "message": "Personal Identity Card Number not correct", "status": "Failure", "router_error": "Internal Server Error", "decision": "retry", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true }' ``` ``` { "connector": "novalnet", "flow": "Authorize", "sub_flow": "sub_flow", "code": "525002", "message": "Personal Identity Card Number not correct", "status": "Failure", "router_error": "Internal Server Error", "decision": "retry", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true, "feature": "retry", "feature_data": { "retry": { "step_up_possible": false, "clear_pan_possible": true, "alternate_network_possible": false, "decision": "retry" } } } ``` DB entry after update <img width="1267" height="326" alt="image" src="https://github.com/user-attachments/assets/421c4fe9-eb73-409b-9810-e7101be63bba" /> ### Test case for the new change where in which we pass feature and feature data in the request ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": true, "clear_pan_possible": true, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "feature": "retry", "feature_data": { "retry": { "step_up_possible": false, "clear_pan_possible": false, "alternate_network_possible": false, "decision": "do_default" } } }' ``` ``` { "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": false, "feature": "retry", "feature_data": { "retry": { "step_up_possible": false, "clear_pan_possible": false, "alternate_network_possible": false, "decision": "do_default" } } } ``` <img width="1221" height="336" alt="image" src="https://github.com/user-attachments/assets/8bd9e48b-4f7b-492a-aacc-9d6d8fd969c4" /> We can see that step_up_possible and clear_pan_possible has been passed as true in the root level whereas it has been passed as false in the feature_data. And in the application response clear_pan_possible and step_up_possible is false in both the places as the values in the feature_data takes precedence. Note :- Same goes for db state and update gsm call -> Update call ``` curl --location 'http://localhost:8080/gsm/update' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": false, "clear_pan_possible": false, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "feature": "retry", "feature_data": { "retry": { "step_up_possible": true, "clear_pan_possible": true, "alternate_network_possible": false, "decision": "do_default" } } }' ``` ``` { "connector": "stripe", "flow": "auth", "sub_flow": "sub_auth", "code": "501", "message": "Server Error", "status": "failed", "router_error": "Internal Server Error", "decision": "do_default", "step_up_possible": true, "unified_code": "5xx", "unified_message": "Error", "error_category": "frm_decline", "clear_pan_possible": true, "feature": "retry", "feature_data": { "retry": { "step_up_possible": true, "clear_pan_possible": true, "alternate_network_possible": false, "decision": "do_default" } } } ``` <img width="1359" height="333" alt="image" src="https://github.com/user-attachments/assets/9e3252ab-4905-4113-a963-999dd6157932" /> -> Test a retry payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key: dev_NZClQhIklvWYnqEzfkfdzGOynCohMCTnkbYrPN0HPkQbm6rTnngnthX51kLWDIn2' \ --data-raw '{ "amount": 1000000, "amount_to_capture": 1000000, "currency": "USD", "confirm": true, "capture_method": "automatic", "setup_future_usage": "on_session", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1753886032", "return_url": "http://127.0.0.1:4040", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "payment_id": "pay_cLWcRqZDJcOaiN3oyxJh", "merchant_id": "merchant_1753885328", "status": "succeeded", "amount": 1000000, "net_amount": 1000000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000000, "connector": "cybersource", "client_secret": "pay_cLWcRqZDJcOaiN3oyxJh_secret_CCZupjoT0zDE6m4s1OCu", "created": "2025-07-30T14:32:41.449Z", "currency": "USD", "customer_id": "cu_1753885961", "customer": { "id": "cu_1753885961", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "avs_response": { "code": "X", "codeRaw": "I1" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_eWHrgeRsB1CJo79hTJVt", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1753885961", "created_at": 1753885961, "expires": 1753889561, "secret": "epk_fa14f011aa934fb29ae59ecdcf6cdd86" }, "manual_retry_allowed": false, "connector_transaction_id": "7538859630876495904805", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_cLWcRqZDJcOaiN3oyxJh_2", "payment_link": null, "profile_id": "pro_OMlZtENVSWshV7Mh9NPv", "surcharge_details": null, "attempt_count": 2, "merchant_decision": null, "merchant_connector_id": "mca_jAKVTh39vFjuD4LN7ZuX", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-30T14:47:41.449Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-30T14:32:43.450Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` ## 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.115.0
794dce168e6b4d280c9c742a6e8a3b3283e09602
794dce168e6b4d280c9c742a6e8a3b3283e09602
juspay/hyperswitch
juspay__hyperswitch-7778
Bug: [DOCS] Updated Intelligent router open api ### Feature Description Updated open api spec for Intelligent router ### Possible Implementation Updated open api spec for Intelligent router ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference/hyperswitch_intelligent_router_open_api_spec.yml b/api-reference/hyperswitch_intelligent_router_open_api_spec.yml index 34eec90726e..341bcc6d209 100644 --- a/api-reference/hyperswitch_intelligent_router_open_api_spec.yml +++ b/api-reference/hyperswitch_intelligent_router_open_api_spec.yml @@ -40,6 +40,10 @@ paths: id: "merchant1" params: "card" labels: ["stripe", "adyen"] + config: + min_aggregates_size: 5 + default_success_rate: 0.95 + specificity_level: ENTITY responses: "200": description: Success rate calculated successfully @@ -84,6 +88,19 @@ paths: application/json: schema: $ref: "#/components/schemas/UpdateSuccessRateWindowRequest" + example: + id: "merchant1" + params: "card" + labels_with_status: + - status: false + label: stripe + - status: true + label: adyen + global_labels_with_status: + - status: false + label: stripe + - status: true + label: adyen responses: "200": description: Window updated successfully @@ -331,6 +348,294 @@ paths: "500": description: Internal server error + /contract_routing.ContractScoreCalculator/FetchContractScore: + post: + summary: Fetch contract scores for an entity + operationId: fetchContractScore + description: Calculates contract scores for an entity based on provided parameters and labels + tags: + - Contract Routing + parameters: + - name: x-tenant-id + in: header + required: true + schema: + type: string + example: public + - name: x-profile-id + in: header + required: true + schema: + type: string + example: pro_WX0giXQnzk2wQJjkKVBX + - name: x-api-key + in: header + required: true + schema: + type: string + example: dev_VLzQTxkPq3ALj2mlfiHL4mMtXca4uplOIOLaKEzmWAmNBXZjwsuv5bCLjnf0QYHm + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CalContractScoreRequest" + example: + id: "merchant1" + params: "card" + labels: ["stripe", "adyen"] + config: + constants: [0.7, 0.3] + time_scale: + time_scale: "Day" + responses: + "200": + description: Success rate calculated successfully + content: + application/json: + schema: + $ref: "#/components/schemas/CalContractScoreResponse" + "400": + description: Invalid request parameters + "500": + description: Internal server error + + /contract_routing.ContractScoreCalculator/UpdateContract: + post: + summary: Update contract information for an entity + operationId: updateContract + description: Updates the contract information for processors based on provided parameters + tags: + - Contract Routing + parameters: + - name: x-tenant-id + in: header + required: true + schema: + type: string + example: public + - name: x-profile-id + in: header + required: true + schema: + type: string + example: pro_WX0giXQnzk2wQJjkKVBX + - name: x-api-key + in: header + required: true + schema: + type: string + example: dev_VLzQTxkPq3ALj2mlfiHL4mMtXca4uplOIOLaKEzmWAmNBXZjwsuv5bCLjnf0QYHm + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateContractRequest" + example: + id: "merchant1" + params: "update" + labels_information: + - label: "stripe" + target_count: 1000 + target_time: 86400 + current_count: 500 + - label: "adyen" + target_count: 1500 + target_time: 86400 + current_count: 750 + responses: + "200": + description: Contract update succeeded + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateContractResponse" + "400": + description: Invalid request parameters + "500": + description: Internal server error + + /contract_routing.ContractScoreCalculator/InvalidateContract: + post: + summary: Invalidate contract information for an entity + operationId: invalidateContract + description: Invalidates the contract for a given entity identifier + tags: + - Contract Routing + parameters: + - name: x-tenant-id + in: header + required: true + schema: + type: string + example: public + - name: x-profile-id + in: header + required: true + schema: + type: string + example: pro_WX0giXQnzk2wQJjkKVBX + - name: x-api-key + in: header + required: true + schema: + type: string + example: dev_VLzQTxkPq3ALj2mlfiHL4mMtXca4uplOIOLaKEzmWAmNBXZjwsuv5bCLjnf0QYHm + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/InvalidateContractRequest" + example: + id: "merchant1" + responses: + "200": + description: Contract invalidation succeeded + content: + application/json: + schema: + $ref: "#/components/schemas/InvalidateContractResponse" + "400": + description: Invalid request parameters + "500": + description: Internal server error + + /euclid.EuclidService/Create: + post: + operationId: CreateRule + summary: Create a routing Rule + description: Creates a routing rule with the given parameters + tags: + - Static Routing + parameters: + - name: x-tenant-id + in: header + required: true + schema: + type: string + example: public + - name: x-profile-id + in: header + required: true + schema: + type: string + example: pro_WX0giXQnzk2wQJjkKVBX + - name: x-api-key + in: header + required: true + schema: + type: string + example: dev_VLzQTxkPq3ALj2mlfiHL4mMtXca4uplOIOLaKEzmWAmNBXZjwsuv5bCLjnf0QYHm + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/RoutingRule" + example: + name: "Test Routing Rule" + algorithm: + globals: {} + default_selection: + priority: + connectors: ["stripe", "adyen", "checkout"] + rules: + - name: "Card Rule" + routing_type: "priority" + output: + priority: + connectors: ["stripe", "adyen"] + statements: + - condition: + - lhs: "payment_method" + comparison: "equal" + value: + enum_variant: "card" + metadata: {} + - lhs: "amount" + comparison: "greater_than" + value: + number: 1000 + metadata: {} + metadata: {} + responses: + "200": + description: Successful creation + content: + application/json: + schema: + $ref: "#/components/schemas/CreateResponse" + example: + algorithm_id: "routing_ec1ac351-7944-440f-bdc7-6a500df1116f" + name: "Test Routing Rule" + created_at: "2025-04-09 8:03:44.85588" + modified_at: "2025-04-09 8:03:44.85588" + "400": + description: Invalid request parameters + "500": + description: Internal server error + + /euclid.EuclidService/Evaluate: + post: + operationId: EvaluateRule + summary: Evaludate an existing routing Rule + description: Evaluates a given routing rule + tags: + - Static Routing + parameters: + - name: x-tenant-id + in: header + required: true + schema: + type: string + example: public + - name: x-profile-id + in: header + required: true + schema: + type: string + example: pro_WX0giXQnzk2wQJjkKVBX + - name: x-api-key + in: header + required: true + schema: + type: string + example: dev_VLzQTxkPq3ALj2mlfiHL4mMtXca4uplOIOLaKEzmWAmNBXZjwsuv5bCLjnf0QYHm + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/EvaluateRequest" + example: + algorithm_id: "routing_ec1ac351-7944-440f-bdc7-6a500df1116f" + parameters: + payment_method: + type: enum_variant + value: "card" + amount: + type: number + value: 2000 + responses: + "200": + description: Evaluation result + content: + application/json: + schema: + $ref: "#/components/schemas/EvaluateResponse" + example: + status: "success" + output: + priority: + connectors: ["stripe", "adyen"] + evaluated_output: + - "stripe" + eligible_connectors: [] + "400": + description: Invalid request parameters + "500": + description: Internal server error + components: schemas: LabelWithScoreList: @@ -366,7 +671,7 @@ components: type: number format: boolean example: true - description: Labels terminal status + description: Label status label: type: string example: stripe @@ -385,25 +690,66 @@ components: - status: true label: adyen + EliminationLabelWithStatus: + type: object + properties: + label: + type: string + example: stripe + elimination_information: + items: + $ref: "#/components/schemas/EliminationInformation" + CalSuccessRateRequest: type: object properties: id: type: string + example: merchant1 description: Entity identifier params: type: string + example: card description: Parameters on which success rate scores has to be maintained labels: type: array + example: ["stripe", "adyen"] items: type: string description: Labels for which to calculate success rates + config: + $ref: "#/components/schemas/CalSuccessRateConfig" required: - id - params - labels + CalSuccessRateConfig: + type: object + required: + - min_aggregates_size + - default_success_rate + properties: + min_aggregates_size: + type: integer + format: uint32 + example: 10 + default_success_rate: + type: number + format: double + example: 0.95 + specificity_level: + $ref: "#/components/schemas/SuccessRateSpecificityLevel" + + SuccessRateSpecificityLevel: + type: string + description: > + Defines the specificity level to be used for calculating the success rate. + enum: + - ENTITY + - GLOBAL + example: ENTITY + CalSuccessRateResponse: type: object properties: @@ -429,11 +775,21 @@ components: items: $ref: "#/components/schemas/LabelWithStatus" description: Entity-specific labels with their success/failure status + example: + - status: false + label: stripe + - status: true + label: adyen global_labels_with_status: type: array items: $ref: "#/components/schemas/LabelWithStatus" description: Global labels with their success/failure status + example: + - status: false + label: stripe + - status: true + label: adyen required: - id - params @@ -471,32 +827,48 @@ components: CalGlobalSuccessRateRequest: type: object + example: + entity_id: "merchant1" + entity_params: "card" + entity_labels: ["stripe", "adyen"] + global_labels: ["visa", "mastercard"] + config: + entity_min_aggregates_size: 10 + entity_default_success_rate: 0.85 properties: entity_id: type: string - example: merchant1 - description: Entity identifier + example: "merchant1" entity_params: type: string - example: card - description: Additional parameters for entity success rate calculation + example: "card" entity_labels: type: array - example: ["stripe", "adyen"] items: type: string - description: Entity-specific labels for which to calculate success rates + example: ["stripe", "adyen"] global_labels: type: array - example: ["stripe", "adyen"] items: type: string - description: Global labels for which to calculate success rates - required: - - entity_id - - entity_params - - entity_labels - - global_labels + example: ["visa", "mastercard"] + config: + $ref: "#/components/schemas/CalGlobalSuccessRateConfig" + + CalGlobalSuccessRateConfig: + type: object + example: + entity_min_aggregates_size: 10 + entity_default_success_rate: 0.85 + properties: + entity_min_aggregates_size: + type: integer + format: uint32 + example: 10 + entity_default_success_rate: + type: number + format: double + example: 0.85 CalGlobalSuccessRateResponse: type: object @@ -517,12 +889,15 @@ components: properties: id: type: string + example: merchant1 description: Entity identifier params: type: string - description: AAdditional parameters for elimination analysis + example: card + description: Additional parameters for elimination analysis labels: type: array + example: ["stripe", "adyen"] items: type: string description: Labels (processors) to check for elimination @@ -539,10 +914,12 @@ components: bucket_size: type: integer format: uint64 + example: 5 description: Maximum failures allowed before elimination bucket_leak_interval_in_secs: type: number format: uint64 + example: 300 description: Time interval after which failures are "forgotten" required: - bucket_size @@ -551,11 +928,23 @@ components: EliminationResponse: type: object properties: - labels_with_score: + labels_with_status: type: array items: - $ref: "#/components/schemas/LabelWithStatus" + $ref: "#/components/schemas/EliminationLabelWithStatus" description: Elimination status for each label + example: + labelsWithStatus: + - label: "stripe" + eliminationInformation: + entity: + isEliminated: true + bucketName: + - "processor_decline" + global: + isEliminated: true + bucketName: + - "processor_decline" EliminationInformation: type: object @@ -584,20 +973,16 @@ components: id: type: string description: "Entity identifier" + example: merchant1 params: type: string description: "Additional parameters" + example: card labels_with_bucket_name: type: array items: - type: object - properties: - label: - type: string - description: "Processor identifier" - bucket_name: - type: string - description: "Bucket to update (failure type)" + $ref: "#/components/schemas/LabelWithBucketName" + example: [{ "label": "stripe", "bucket_name": "processor_decline" }] config: $ref: "#/components/schemas/EliminationBucketConfig" required: @@ -651,3 +1036,495 @@ components: - BUCKET_INVALIDATION_FAILED required: - status + + CalContractScoreRequest: + type: object + properties: + id: + type: string + description: Entity identifier + example: merchant1 + params: + type: string + description: Additional parameters for contract calculation + example: card + labels: + type: array + items: + type: string + description: Labels (processors) to calculate scores for + example: ["stripe", "adyen"] + config: + $ref: "#/components/schemas/CalContractScoreConfig" + description: Configuration for calculation + required: + - id + - labels + - config + + CalContractScoreConfig: + type: object + properties: + constants: + type: array + items: + type: number + format: double + description: Constants used in score calculation algorithm + example: [0.7, 0.3] + time_scale: + $ref: "#/components/schemas/TimeScale" + description: Time scale for contract calculation + required: + - constants + - time_scale + + TimeScale: + type: object + properties: + time_scale: + type: string + enum: + - Day + - Month + description: Selected time scale for contract calculation + + CalContractScoreResponse: + type: object + properties: + labels_with_score: + type: array + items: + $ref: "#/components/schemas/ScoreData" + description: Contract scores for each label + + ScoreData: + type: object + properties: + score: + type: number + format: double + description: Contract score (higher values indicate higher priority) + example: 0.95 + label: + type: string + description: Label (processor) identifier + example: stripe + current_count: + type: integer + format: uint64 + description: Current transaction count for this processor + example: 500 + required: + - score + - label + - current_count + + UpdateContractRequest: + type: object + properties: + id: + type: string + description: Entity identifier + example: merchant1 + params: + type: string + description: Additional parameters + example: card + labels_information: + type: array + items: + $ref: "#/components/schemas/LabelInformation" + description: Contract information for processors + example: + - label: stripe + target_count: 1000 + target_time: 86400 + current_count: 500 + - label: adyen + target_count: 1500 + target_time: 86400 + current_count: 750 + required: + - id + - labels_information + + LabelInformation: + type: object + properties: + label: + type: string + description: Processor identifier + example: stripe + target_count: + type: integer + format: uint64 + description: Target transaction count in contract + example: 10000 + target_time: + type: integer + format: uint64 + description: Time period for the target (in seconds) + example: 1744803903 + current_count: + type: integer + format: uint64 + description: Current transaction count + example: 500 + required: + - label + - target_count + - target_time + - current_count + + UpdateContractResponse: + type: object + properties: + status: + type: string + enum: + - CONTRACT_UPDATION_SUCCEEDED + - CONTRACT_UPDATION_FAILED + description: Status of the update operation + required: + - status + + InvalidateContractRequest: + type: object + properties: + id: + type: string + description: Entity identifier to invalidate + example: merchant1 + required: + - id + + InvalidateContractResponse: + type: object + properties: + status: + type: string + enum: + - CONTRACT_INVALIDATION_SUCCEEDED + - CONTRACT_INVALIDATION_FAILED + description: Status of the invalidation operation + required: + - status + + RoutingRule: + type: object + example: + algorithm: + globals: {} + default_selection: + priority: + connectors: ["stripe", "adyen", "checkout"] + rules: + - name: "Card Rule" + routing_type: "priority" + output: + priority: + connectors: ["stripe", "adyen"] + statements: + - condition: + - lhs: "payment_method" + comparison: "equal" + value: + enum_variant: "card" + metadata: {} + - lhs: "amount" + comparison: "greater_than" + value: + number: 1000 + metadata: {} + metadata: {} + properties: + name: + type: string + example: Test Routing Rule + algorithm: + $ref: "#/components/schemas/Program" + + CreateResponse: + type: object + properties: + algorithm_id: + type: string + description: Algorithm Id for the routing rule + example: routing_ec1ac351-7944-440f-bdc7-6a500df1116f + name: + type: string + description: name of the routing rule + example: test routing rule + created_at: + type: string + description: Timestamp for creation of routing rule + example: "2025-04-09 8:03:44.85588" + modified_at: + type: string + description: Timestamp for modification of routing rule + example: "2025-04-09 8:03:44.85588" + + EvaluateRequest: + type: object + example: + algorithm_id: routing_ec1ac351-7944-440f-bdc7-6a500df1116f + parameters: + payment_method: + type: enum_variant + value: "card" + amount: + type: number + value: 1500 + properties: + algorithm_id: + type: string + example: routing_ec1ac351-7944-440f-bdc7-6a500df1116f + parameters: + type: object + example: + payment_method: + type: enum_variant + value: "card" + amount: + type: number + value: 1500 + additionalProperties: + $ref: "#/components/schemas/ValueType" + + EvaluateResponse: + type: object + example: + status: "success" + output: + priority: + connectors: ["stripe", "adyen"] + evaluated_output: ["stripe", "adyen"] + eligible_connectors: ["stripe", "adyen", "checkout"] + properties: + status: + type: string + output: + $ref: "#/components/schemas/Output" + evaluated_output: + type: array + items: + type: string + eligible_connectors: + type: array + items: + type: string + + Program: + type: object + example: + globals: {} + default_selection: + priority: + connectors: ["stripe", "checkout"] + rules: + - name: High Amount Card + routing_type: priority + output: + priority: + connectors: ["adyen"] + statements: + - condition: + - lhs: "payment_method" + comparison: equal + value: "card" + metadata: {} + - lhs: "amount" + comparison: greater_than + value: 1000 + metadata: {} + metadata: {} + properties: + globals: + type: object + additionalProperties: + $ref: "#/components/schemas/ValueTypeList" + default_selection: + $ref: "#/components/schemas/Output" + rules: + type: array + items: + $ref: "#/components/schemas/Rule" + metadata: + type: object + additionalProperties: + $ref: "#/components/schemas/MetadataValue" + + Rule: + type: object + example: + name: High Volume Transactions + routing_type: priority + output: + priority: + connectors: ["stripe", "adyen"] + statements: + - condition: + - lhs: amount + comparison: greater_than + value: 5000 + metadata: {} + properties: + name: + type: string + routing_type: + $ref: "#/components/schemas/RoutingType" + output: + $ref: "#/components/schemas/Output" + statements: + type: array + items: + $ref: "#/components/schemas/IfStatement" + + RoutingType: + type: string + enum: [priority, volume_split, volume_split_priority] + + Output: + type: object + oneOf: + - $ref: "#/components/schemas/PriorityOutput" + - $ref: "#/components/schemas/VolumeSplitOutput" + - $ref: "#/components/schemas/VolumeSplitPriorityOutput" + + PriorityOutput: + type: object + example: + connectors: ["stripe", "adyen"] + properties: + connectors: + type: array + items: + type: string + + VolumeSplitOutput: + type: object + properties: + connectors: + type: array + items: + $ref: "#/components/schemas/VolumeSplit" + + VolumeSplitPriorityOutput: + type: object + example: + groups: + - split: 60 + output: ["stripe", "adyen"] + - split: 40 + output: ["checkout"] + properties: + groups: + type: array + items: + $ref: "#/components/schemas/VolumeSplitGroup" + + VolumeSplit: + type: object + example: + split: 70 + output: "stripe" + properties: + split: + type: integer + output: + type: string + + VolumeSplitGroup: + type: object + example: + split: 50 + output: ["adyen", "checkout"] + properties: + split: + type: integer + output: + type: array + items: + type: string + + IfStatement: + type: object + example: + condition: + - lhs: "currency" + comparison: equal + value: "USD" + metadata: {} + nested: + - condition: + - lhs: "amount" + comparison: greater_than + value: 1000 + metadata: {} + properties: + condition: + type: array + items: + $ref: "#/components/schemas/Comparison" + nested: + type: array + items: + $ref: "#/components/schemas/IfStatement" + + Comparison: + type: object + example: + lhs: "payment_method" + comparison: equal + value: "card" + metadata: {} + properties: + lhs: + type: string + comparison: + $ref: "#/components/schemas/ComparisonType" + value: + $ref: "#/components/schemas/ValueType" + metadata: + type: object + additionalProperties: + $ref: "#/components/schemas/MetadataValue" + + ComparisonType: + type: string + enum: + [ + equal, + not_equal, + less_than, + less_than_equal, + greater_than, + greater_than_equal, + ] + + ValueTypeList: + type: object + example: + values: ["card", "bank_transfer"] + properties: + values: + type: array + items: + $ref: "#/components/schemas/ValueType" + + ValueType: + type: object + oneOf: + - type: integer + format: uint64 + - type: string + - $ref: "#/components/schemas/MetadataValue" + + MetadataValue: + type: object + properties: + key: + type: string + value: + type: string diff --git a/api-reference/intelligent-router-api-reference/contract-routing/fetch-contract-scores-for-an-entity.mdx b/api-reference/intelligent-router-api-reference/contract-routing/fetch-contract-scores-for-an-entity.mdx new file mode 100644 index 00000000000..2fcb03e7ce2 --- /dev/null +++ b/api-reference/intelligent-router-api-reference/contract-routing/fetch-contract-scores-for-an-entity.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /contract_routing.ContractScoreCalculator/FetchContractScore +--- \ No newline at end of file diff --git a/api-reference/intelligent-router-api-reference/contract-routing/invalidate-contract-information-for-an-entity.mdx b/api-reference/intelligent-router-api-reference/contract-routing/invalidate-contract-information-for-an-entity.mdx new file mode 100644 index 00000000000..a84626aacce --- /dev/null +++ b/api-reference/intelligent-router-api-reference/contract-routing/invalidate-contract-information-for-an-entity.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /contract_routing.ContractScoreCalculator/InvalidateContract +--- \ No newline at end of file diff --git a/api-reference/intelligent-router-api-reference/contract-routing/update-contract-information-for-an-entity.mdx b/api-reference/intelligent-router-api-reference/contract-routing/update-contract-information-for-an-entity.mdx new file mode 100644 index 00000000000..12792226e76 --- /dev/null +++ b/api-reference/intelligent-router-api-reference/contract-routing/update-contract-information-for-an-entity.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /contract_routing.ContractScoreCalculator/UpdateContract +--- \ No newline at end of file diff --git a/api-reference/intelligent-router-api-reference/static-routing/create-a-routing-rule.mdx b/api-reference/intelligent-router-api-reference/static-routing/create-a-routing-rule.mdx new file mode 100644 index 00000000000..ac990940c87 --- /dev/null +++ b/api-reference/intelligent-router-api-reference/static-routing/create-a-routing-rule.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /euclid.EuclidService/Create +--- \ No newline at end of file diff --git a/api-reference/intelligent-router-api-reference/static-routing/evaluate-routing-rule.mdx b/api-reference/intelligent-router-api-reference/static-routing/evaluate-routing-rule.mdx new file mode 100644 index 00000000000..02f78919f26 --- /dev/null +++ b/api-reference/intelligent-router-api-reference/static-routing/evaluate-routing-rule.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /euclid.EuclidService/Evaluate +--- \ No newline at end of file diff --git a/api-reference/mint.json b/api-reference/mint.json index ac6996705a1..aafbb5221c1 100644 --- a/api-reference/mint.json +++ b/api-reference/mint.json @@ -10,7 +10,7 @@ "name": "Contact Us", "url": "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw" } - ], + ], "topbarCtaButton": { "type": "link", "url": "https://docs.hyperswitch.io/hyperswitch-open-source/overview", @@ -41,7 +41,9 @@ "navigation": [ { "group": "Get Started", - "pages": ["introduction"] + "pages": [ + "introduction" + ] }, { "group": "Essentials", @@ -145,7 +147,9 @@ }, { "group": "Poll", - "pages": ["api-reference/poll/poll--retrieve-poll-status"] + "pages": [ + "api-reference/poll/poll--retrieve-poll-status" + ] }, { "group": "Blocklist", @@ -180,7 +184,9 @@ }, { "group": "Schemas", - "pages": ["api-reference/schemas/outgoing--webhook"] + "pages": [ + "api-reference/schemas/outgoing--webhook" + ] } ] }, @@ -256,14 +262,18 @@ }, { "group": "Hyperswitch Card Vault", - "pages": ["locker-api-reference/overview"] + "pages": [ + "locker-api-reference/overview" + ] }, { "group": "API Reference", "pages": [ { "group": "Locker - Health", - "pages": ["locker-api-reference/locker-health/get-health"] + "pages": [ + "locker-api-reference/locker-health/get-health" + ] }, { "group": "Locker - Key Custodian", @@ -286,7 +296,9 @@ }, { "group": "Hyperswitch Intelligent Router", - "pages": ["intelligent-router-api-reference/overview"] + "pages": [ + "intelligent-router-api-reference/overview" + ] }, { "group": "API Reference", @@ -307,6 +319,21 @@ "intelligent-router-api-reference/elimination/update-elimination-bucket", "intelligent-router-api-reference/elimination/invalidate-elimination-bucket" ] + }, + { + "group": "Contract Routing", + "pages": [ + "intelligent-router-api-reference/contract-routing/fetch-contract-scores-for-an-entity", + "intelligent-router-api-reference/contract-routing/update-contract-information-for-an-entity", + "intelligent-router-api-reference/contract-routing/invalidate-contract-information-for-an-entity" + ] + }, + { + "group": "Static Routing", + "pages": [ + "intelligent-router-api-reference/static-routing/create-a-routing-rule", + "intelligent-router-api-reference/static-routing/evaluate-routing-rule" + ] } ] } @@ -315,7 +342,10 @@ "github": "https://github.com/juspay/hyperswitch", "linkedin": "https://www.linkedin.com/company/hyperswitch" }, - "openapi": ["openapi_spec.json", "rust_locker_open_api_spec.yml"], + "openapi": [ + "openapi_spec.json", + "rust_locker_open_api_spec.yml" + ], "api": { "maintainOrder": true },
2025-04-09T14:10:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [x] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Updated open-api spec for Intelligent routing ### 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="1728" alt="image" src="https://github.com/user-attachments/assets/63adbc60-e89b-417f-ad4e-b8241ebdebbf" /> <img width="1728" alt="image" src="https://github.com/user-attachments/assets/2a50d145-c50b-4aba-b9ce-e19a67416b6c" /> <img width="1728" alt="image" src="https://github.com/user-attachments/assets/112ca2eb-d015-43e1-a916-6ea76227ab80" /> <img width="1728" alt="image" src="https://github.com/user-attachments/assets/9714570d-c8e6-41ce-932d-3562a5fc9603" /> ## 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.113.0
ec147d5e7316c5fa5a5ac90ca7bc9318dc2dcaab
ec147d5e7316c5fa5a5ac90ca7bc9318dc2dcaab
juspay/hyperswitch
juspay__hyperswitch-7764
Bug: `nmi` tests shows different error messages for the same request Postman Tests for nmi behaves like the following while running `Flow Testcases/Variation Cases/Scenario9-Create a mandate payment` ## Creating a mandate payment for `nmi` ```curl curl --location '{{baseUrl}}/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{apiKey}}' \ --data-raw '{ "amount": 47074, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 47074, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "10", "card_exp_year": "69", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "setup_future_usage": "off_session", "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 7000, "currency": "USD" } } }, "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2022-09-10T10:11:12Z", "online": { "ip_address": "123.32.25.123", "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ### Integ Response ```json { "error": { "type": "invalid_request", "message": "Payment method type not supported", "code": "IR_19", "reason": "credit mandate payment is not supported by nmi" } } ``` ### SBX Response ```json { "error": { "type": "invalid_request", "message": "Payment method type not supported", "code": "IR_19", "reason": "debit mandate payment is not supported by nmi" } } ``` It shows different error messages for two environments.
diff --git a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js index b07811aed26..656033c2caa 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js +++ b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js @@ -34,7 +34,7 @@ if (jsonData?.error?.type) { // Response body should have value "mandate payment is not supported by nmi" for "error reason" if (jsonData?.error?.message) { pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'error.reason' matches ' mandate payment is not supported by nmi'" , + "[POST]::/payments/:id/confirm - Content check if value for 'error.reason' matches 'credit mandate payment is not supported by nmi'" , function () { pm.expect(jsonData.error.reason).to.eql("credit mandate payment is not supported by nmi"); }, diff --git a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/request.json index 314752373cc..884b99e89f7 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/request.json @@ -35,7 +35,7 @@ "payment_method": "card", "payment_method_data": { "card": { - "card_number": "4111111111111111", + "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "69", "card_holder_name": "joseph Doe",
2025-04-08T11:09:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> Postman Tests for `nmi` were failing on SBX (but not on Integ) because `Flow Testcases/Variation Cases/Scenario9-Create a mandate payment` responded an error message as `debit mandate payment is not supported by nmi` on SBX and `credit mandate payment is not supported by nmi` on Integ when we are using Card `4111111111111111`. So, I thought of two solutions. First, check whether the error message contains "mandate payment is not supported by nmi" or second, change the card number for which the error message in both the environments are same. I chose the second way finally. And, there is a slight change, which I missed in #7159. <!-- However, I made a change in #7159, which goes like the following ![image](https://github.com/user-attachments/assets/62b3ed2a-bbe2-426f-8a30-eb4f980b51ba) Because it was failing expecting the error message to be " mandate payment is not supported by nmi" but it should include the same instead of equal to. --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The `Flow Testcases/Variation Cases/Scenario9-Create a mandate payment` passing on Integ and failing on SBX. #7764 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### Before | Integ | Sandbox | | -------- | ------- | | <img width="850" alt="image" src="https://github.com/user-attachments/assets/c66e4b3b-5cf3-49ee-998a-fe7ab388c0f9" /> | <img width="850" alt="image" src="https://github.com/user-attachments/assets/4a26f840-405b-41e8-86f2-3be32aa88056" /> | ### After | Integ | Sandbox | | -------- | ------- | | <img width="850" alt="image" src="https://github.com/user-attachments/assets/eb2b3d92-0431-4887-86a9-53f5db6be2eb" /> | <img width="850" alt="image" src="https://github.com/user-attachments/assets/e0334b87-9bf7-43ab-b20e-fdd87e5531c7" /> | ## 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.113.0
8738f190677c25e9023e2faa2be9aa9a60ce1097
8738f190677c25e9023e2faa2be9aa9a60ce1097
juspay/hyperswitch
juspay__hyperswitch-7767
Bug: Modify List Merchant Accounts in Org with org_id (v1) Modify List Merchant Accounts in Org with org_id (v1) as v2 merchant accounts will hav merchant_id as `Null`, and they cant be deserialized into v1. This will cause terminate_2fa API to fail and cant obtain the merchant_id required to generate the jwt token.
diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rs index c40af7f6535..ab51953b6ef 100644 --- a/crates/diesel_models/src/query/merchant_account.rs +++ b/crates/diesel_models/src/query/merchant_account.rs @@ -1,4 +1,5 @@ -use diesel::{associations::HasTable, ExpressionMethods, Table}; +use common_types::consts::API_VERSION; +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; #[cfg(feature = "v1")] @@ -101,7 +102,9 @@ impl MerchantAccount { _, >( conn, - dsl::organization_id.eq(organization_id.to_owned()), + dsl::organization_id + .eq(organization_id.to_owned()) + .and(dsl::version.eq(API_VERSION)), None, None, None,
2025-04-10T08:32:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Modified the v1 merchant list query to list only v1 merchant accounts, v2 merchants cannot deserialize in v1 application code. This change is required, since now, both v1 and v2 merchant accounts are stored in the same schema. This will affect the following flows: - list merchant accounts for user in org - list merchant accounts (admin API) - get single merchant id (during sign-in, to create JWT token) - switch org for user ### 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). --> Fix the deserialization issues when listing merchant accounts using v1 routes. ## 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)? --> Hit the following curls after creating a v1 merchant account and a v2 merchant account in the same organization. The following APIs should only return v1 merchant accounts in the organization (and not the v2 merchant accounts). #### List Merchant Accounts for User in Org: ```bash curl --location 'http://localhost:8080/user/list/merchant' \ --header 'x-feature: integ-custom' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMGVkNzFkOTktYjhiMS00ODI3LWEyMDgtOTUyZjY1NDNmMDY3IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjI1Njc2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDM5ODQ5Mywib3JnX2lkIjoib3JnX0dYbXNobWtubDlrMGFuOXAzc3A3IiwicHJvZmlsZV9pZCI6InByb19JOUZVMTlSdWp0NzI4SFp0ODB4MyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.q9-E0Wb8IXrwUvQyw5A2-bvgwkXqUeZrKsRi_rTHnaE' ``` #### Sign in and Terminate 2fa: (while sign-in, to create the jwt user-info token): - Sign-in: ```bash curl --location 'http://localhost:8080/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "[email protected]", "password": "Hyperswitch@123" }' ``` - Terminate 2fa: ```bash curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMGVkNzFkOTktYjhiMS00ODI3LWEyMDgtOTUyZjY1NDNmMDY3IiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX3VwIiwicGF0aCI6W10sImV4cCI6MTc0NDM5ODQ3NiwidGVuYW50X2lkIjoicHVibGljIn0.1p4cqrxgCDvPde5vq7nuuvApXQkaeoZX7ThvMFeiqFU' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMGVkNzFkOTktYjhiMS00ODI3LWEyMDgtOTUyZjY1NDNmMDY3IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjI1Njc2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDM5ODQ5Mywib3JnX2lkIjoib3JnX0dYbXNobWtubDlrMGFuOXAzc3A3IiwicHJvZmlsZV9pZCI6InByb19JOUZVMTlSdWp0NzI4SFp0ODB4MyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.q9-E0Wb8IXrwUvQyw5A2-bvgwkXqUeZrKsRi_rTHnaE' ``` #### Switch Org for User (for tenant level): ```bash curl --location 'https://integ-api.hyperswitch.io/user/switch/org' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMGVkNzFkOTktYjhiMS00ODI3LWEyMDgtOTUyZjY1NDNmMDY3IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ0MjI1Njc2Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0NDM5ODQ5Mywib3JnX2lkIjoib3JnX0dYbXNobWtubDlrMGFuOXAzc3A3IiwicHJvZmlsZV9pZCI6InByb19JOUZVMTlSdWp0NzI4SFp0ODB4MyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.q9-E0Wb8IXrwUvQyw5A2-bvgwkXqUeZrKsRi_rTHnaE' \ --data '{ "org_id": "some_org_id" }' ``` #### List Merchant Accounts (Admin API): ```bash curl --location 'https://integ.hyperswitch.io/api/accounts/list?organization_id=org_pEDRnaMediEZaJcU888G' \ --header 'api-key: <admin-api-key>' ``` ## 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.113.0
7088fd565e426375d54c95e64e58ba6cadc414a7
7088fd565e426375d54c95e64e58ba6cadc414a7
juspay/hyperswitch
juspay__hyperswitch-7761
Bug: One click docker setup A script is needed to ensure one click docker setup, to minimise issues faced by users. > Run the whole setup with simple command > Show output with localhost links for different setups
diff --git a/README.md b/README.md index 72ac7e0e3a7..7f15ac2b01c 100644 --- a/README.md +++ b/README.md @@ -78,36 +78,17 @@ Read more at [Hyperswitch docs](https://docs.hyperswitch.io/). ### 1. Local Setup You can run Hyperswitch on your system using Docker compose after cloning this repository. - +We recommend using Docker Desktop (Or Orbstack) for Windows and Mac OS. On Linux, you can install Docker Engine directly. ```shell git clone --depth 1 --branch latest https://github.com/juspay/hyperswitch cd hyperswitch docker compose up -d +# This script verifies the setup and provides links to the individual components. +scripts/docker_output.sh ``` +The next step is to [configure a connector][configure-a-connector] with the Hyperswitch Control Center and [try a payment][try-a-payment]. -Check out the [local setup guide][local-setup-guide] for a more details on setting up the entire stack or component wise. This takes 15-mins and gives the following output -```shell -[+] Running 2/2 -✔ hyperswitch-control-center Pulled 2.9s -✔ hyperswitch-server Pulled 3.0s -[+] Running 6/0 - -✔ Container hyperswitch-pg-1 Created 0.0s -✔ Container hyperswitch-redis-standalone-1 Created 0.0s -✔ Container hyperswitch-migration_runner-1 Created 0.0s -✔ Container hyperswitch-hyperswitch-server-1 Created 0.0s -✔ Container hyperswitch-hyperswitch-web-1 Created 0.0s -✔ Container hyperswitch-hyperswitch-control-center-1 Created 0.0s - -Attaching to hyperswitch-control-center-1, hyperswitch-server-1, hyperswitch-web-1, migration_runner-1, pg-1, redis-standalone-1 -``` -You've now setup Hyperswitch in your local machine. In order to verify that the server is up and running hit the health endpoint: -```shell -curl --head --request GET 'http://localhost:8080/health' -``` -The expected response here is a `200 OK` status code. This indicates that the server and all of its dependent services are functioning correctly. -Now, you can access the Control Center in your browser at `http://localhost:9000`. -The next step is to configure a connector with the Hyperswitch Control Center and try a payment. +Check out the [local setup guide][local-setup-guide] for more details on setting up the entire stack or component wise. ### 2. Deployment on cloud @@ -144,7 +125,8 @@ You can experience the product by signing up for our [hosted sandbox](https://ap [learning-resources]: https://docs.hyperswitch.io/learn-more/payment-flows [local-setup-guide]: /docs/try_local_system.md [docker-compose-scheduler-monitoring]: /docs/try_local_system.md#running-additional-services - +[configure-a-connector]: https://docs.hyperswitch.io/hyperswitch-open-source/account-setup/using-hyperswitch-control-center#add-a-payment-processor +[try-a-payment]: https://docs.hyperswitch.io/hyperswitch-open-source/account-setup/test-a-payment <a href="support-feature-requests"> <h2 id="support-feature-requests">Support, Feature requests & Bugs</h2> diff --git a/scripts/docker_output.sh b/scripts/docker_output.sh new file mode 100755 index 00000000000..80d178ca75b --- /dev/null +++ b/scripts/docker_output.sh @@ -0,0 +1,33 @@ +#! /usr/bin/env bash +set -euo pipefail + +# Define the URL to check service availability (adjust HOST and PORT if needed) +HOST="localhost" +PORT="8080" +SERVICE_URL="http://${HOST}:${PORT}/health" + +MAX_RETRIES=70 +RETRY_COUNT=0 + +# Wait until the service is available or retries are exhausted +while ! curl --silent --fail "${SERVICE_URL}" > /dev/null; do + if (( RETRY_COUNT >= MAX_RETRIES )); then + echo "" + echo "Service failed to start. Kindly check the logs." + echo "You can view the logs using the command: docker-compose logs -f <service name>" + exit 1 + fi + printf "." + sleep 2 + ((RETRY_COUNT++)) +done + +# Define ANSI 24-bit (true color) escape sequences for Light Sky Blue +LIGHT_SKY_BLUE="\033[38;2;135;206;250m" +RESET="\033[0m" + +# Print the service URLs with only the links colored +echo -e "Control Centre running at ${LIGHT_SKY_BLUE}http://localhost:9000${RESET}" +echo -e "App server running at ${LIGHT_SKY_BLUE}http://localhost:8080${RESET}" +echo -e "Web-SDK running at ${LIGHT_SKY_BLUE}http://localhost:5252/HyperLoader.js${RESET}" +echo -e "Mailhog running at ${LIGHT_SKY_BLUE}http://localhost:8025${RESET}" \ No newline at end of file
2025-04-08T08:30:51Z
## 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 --> Script for one click docker setup, to minimise issues faced by users. >Run the whole setup with simple command >Show output with localhost links for different setups ### 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). --> Script for one click docker setup, to minimise issues faced by users. Closes #7761 ## 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)? --> Attaching ss of test on local. <img width="466" alt="Screenshot 2025-04-08 at 4 12 13 PM" src="https://github.com/user-attachments/assets/003ce4e1-aadc-4ad2-abde-763728f51ad1" /> ## 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.113.0
d6c26c5d75652a2ba2ecfbc0df7d33172df1705b
d6c26c5d75652a2ba2ecfbc0df7d33172df1705b
juspay/hyperswitch
juspay__hyperswitch-7769
Bug: feat(vsaas): add processor_merchant_id and created_by column in payment_intents and payments_attempts for v1 Tracking issue #1: https://github.com/juspay/hyperswitch-control-center/issues/2544 Tracking issue #2: https://github.com/juspay/hyperswitch-control-center/issues/2546
diff --git a/crates/common_utils/src/macros.rs b/crates/common_utils/src/macros.rs index 2ab0560cd41..8dcffbb6643 100644 --- a/crates/common_utils/src/macros.rs +++ b/crates/common_utils/src/macros.rs @@ -437,3 +437,387 @@ macro_rules! type_name { .unwrap_or_default(); }; } + +/// **Note** Creates an enum wrapper that implements `FromStr`, `Display`, `Serialize`, and `Deserialize` +/// based on a specific string representation format: `"VariantName<delimiter>FieldValue"`. +/// It handles parsing errors by returning a dedicated `Invalid` variant. +/// *Note*: The macro adds `Invalid,` automatically. +/// +/// # Use Case +/// +/// This macro is designed for scenarios where you need an enum, with each variant +/// holding a single piece of associated data, to be easily convertible to and from +/// a simple string format. This is useful for cases where enum is serialized to key value pairs +/// +/// It avoids more complex serialization structures (like JSON objects `{"VariantName": value}`) +/// in favor of a plain string representation. +/// +/// # Input Enum Format and Constraints +/// +/// To use this macro, the enum definition must adhere to the following structure: +/// +/// 1. **Public Enum:** The enum must be declared as `pub enum EnumName { ... }`. +/// 2. **Struct Variants Only:** All variants must be struct variants (using `{}`). +/// 3. **Exactly One Field:** Each struct variant must contain *exactly one* named field. +/// * **Valid:** `VariantA { value: i32 }` +/// * **Invalid:** `VariantA(i32)` (tuple variant) +/// * **Invalid:** `VariantA` or `VariantA {}` (no field) +/// * **Invalid:** `VariantA { value: i32, other: bool }` (multiple fields) +/// 4. **Tag Delimiter:** The macro invocation must specify a `tag_delimeter` literal, +/// which is the character used to separate the variant name from the field data in +/// the string representation (e.g., `tag_delimeter = ":",`). +/// 5. **Field Type Requirements:** The type of the single field in each variant (`$field_ty`) +/// must implement: +/// * `core::str::FromStr`: To parse the field's data from the string part. +/// The `Err` type should ideally be convertible to a meaningful error, though the +/// macro currently uses a generic error message upon failure. +/// * `core::fmt::Display`: To convert the field's data into the string part. +/// * `serde::Serialize` and `serde::Deserialize<'de>`: Although the macro implements +/// custom `Serialize`/`Deserialize` for the *enum* using the string format, the field +/// type itself must satisfy these bounds if required elsewhere or by generic contexts. +/// The macro's implementations rely solely on `Display` and `FromStr` for the conversion. +/// 6. **Error Type:** This macro uses `core::convert::Infallible` as it never fails but gives +/// `Self::Invalid` variant. +/// +/// # Serialization and Deserialization (`serde`) +/// +/// When `serde` features are enabled and the necessary traits are derived or implemented, +/// this macro implements `Serialize` and `Deserialize` for the enum: +/// +/// **Serialization:** An enum value like `MyEnum::VariantA { value: 123 }` (with `tag_delimeter = ":",`) +/// will be serialized into the string `"VariantA:123"`. If serializing to JSON, this results +/// in a JSON string: `"\"VariantA:123\""`. +/// **Deserialization:** The macro expects a string matching the format `"VariantName<delimiter>FieldValue"`. +/// It uses the enum's `FromStr` implementation internally. When deserializing from JSON, it +/// expects a JSON string containing the correctly formatted value (e.g., `"\"VariantA:123\""`). +/// +/// # `Display` and `FromStr` +/// +/// **`Display`:** Formats valid variants to `"VariantName<delimiter>FieldValue"` and catch-all cases to `"Invalid"`. +/// **`FromStr`:** Parses `"VariantName<delimiter>FieldValue"` to the variant, or returns `Self::Invalid` +/// if the input string is malformed or `"Invalid"`. +/// +/// # Example +/// +/// ```rust +/// use std::str::FromStr; +/// +/// crate::impl_enum_str!( +/// tag_delimeter = ":", +/// #[derive(Debug, PartialEq, Clone)] // Add other derives as needed +/// pub enum Setting { +/// Timeout { duration_ms: u32 }, +/// Username { name: String }, +/// } +/// ); +/// // Note: The macro adds `Invalid,` automatically. +/// +/// fn main() { +/// // Display +/// let setting1 = Setting::Timeout { duration_ms: 5000 }; +/// assert_eq!(setting1.to_string(), "Timeout:5000"); +/// assert_eq!(Setting::Invalid.to_string(), "Invalid"); +/// +/// // FromStr (returns Self, not Result) +/// let parsed_setting: Setting = "Username:admin".parse().expect("Valid parse"); // parse() itself doesn't panic +/// assert_eq!(parsed_setting, Setting::Username { name: "admin".to_string() }); +/// +/// let invalid_format: Setting = "Timeout".parse().expect("Parse always returns Self"); +/// assert_eq!(invalid_format, Setting::Invalid); // Malformed input yields Invalid +/// +/// let bad_data: Setting = "Timeout:fast".parse().expect("Parse always returns Self"); +/// assert_eq!(bad_data, Setting::Invalid); // Bad field data yields Invalid +/// +/// let unknown_tag: Setting = "Unknown:abc".parse().expect("Parse always returns Self"); +/// assert_eq!(unknown_tag, Setting::Invalid); // Unknown tag yields Invalid +/// +/// let explicit_invalid: Setting = "Invalid".parse().expect("Parse always returns Self"); +/// assert_eq!(explicit_invalid, Setting::Invalid); // "Invalid" string yields Invalid +/// +/// // Serde (requires derive Serialize/Deserialize on Setting) +/// // let json_output = serde_json::to_string(&setting1).unwrap(); +/// // assert_eq!(json_output, "\"Timeout:5000\""); +/// // let invalid_json_output = serde_json::to_string(&Setting::Invalid).unwrap(); +/// // assert_eq!(invalid_json_output, "\"Invalid\""); +/// +/// // let deserialized: Setting = serde_json::from_str("\"Username:guest\"").unwrap(); +/// // assert_eq!(deserialized, Setting::Username { name: "guest".to_string() }); +/// // let deserialized_invalid: Setting = serde_json::from_str("\"Invalid\"").unwrap(); +/// // assert_eq!(deserialized_invalid, Setting::Invalid); +/// // let deserialized_malformed: Setting = serde_json::from_str("\"TimeoutFast\"").unwrap(); +/// // assert_eq!(deserialized_malformed, Setting::Invalid); // Malformed -> Invalid +/// } +/// +/// # // Mock macro definition for doctest purposes +/// # #[macro_export] macro_rules! impl_enum_str { ($($tt:tt)*) => { $($tt)* } } +/// ``` +#[macro_export] +macro_rules! impl_enum_str { + ( + tag_delimeter = $tag_delim:literal, + $(#[$enum_attr:meta])* + pub enum $enum_name:ident { + $( + $(#[$variant_attr:meta])* + $variant:ident { + $(#[$field_attr:meta])* + $field:ident : $field_ty:ty $(,)? + } + ),* $(,)? + } + ) => { + $(#[$enum_attr])* + pub enum $enum_name { + $( + $(#[$variant_attr])* + $variant { + $(#[$field_attr])* + $field : $field_ty + }, + )* + /// Represents a parsing failure. + Invalid, // Automatically add the Invalid variant + } + + // Implement FromStr - now returns Self, not Result + impl core::str::FromStr for $enum_name { + // No associated error type needed + type Err = core::convert::Infallible; // FromStr requires an Err type, use Infallible + + fn from_str(s: &str) -> Result<Self, Self::Err> { + // Check for explicit "Invalid" string first + if s == "Invalid" { + return Ok(Self::Invalid); + } + + let Some((tag, associated_data)) = s.split_once($tag_delim) else { + // Missing delimiter -> Invalid + return Ok(Self::Invalid); + }; + + let result = match tag { + $( + stringify!($variant) => { + // Try to parse the field data + match associated_data.parse::<$field_ty>() { + Ok(parsed_field) => { + // Success -> construct the variant + Self::$variant { $field: parsed_field } + }, + Err(_) => { + // Field parse failure -> Invalid + Self::Invalid + } + } + } + ),* + // Unknown tag -> Invalid + _ => Self::Invalid, + }; + Ok(result) // Always Ok because failure modes return Self::Invalid + } + } + + // Implement Serialize + impl ::serde::Serialize for $enum_name { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: ::serde::Serializer, + { + match self { + $( + Self::$variant { $field } => { + let s = format!("{}{}{}", stringify!($variant), $tag_delim, $field); + serializer.serialize_str(&s) + } + )* + // Handle Invalid variant + Self::Invalid => serializer.serialize_str("Invalid"), + } + } + } + + // Implement Deserialize + impl<'de> ::serde::Deserialize<'de> for $enum_name { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: ::serde::Deserializer<'de>, + { + struct EnumVisitor; + + impl<'de> ::serde::de::Visitor<'de> for EnumVisitor { + type Value = $enum_name; + + fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + formatter.write_str(concat!("a string like VariantName", $tag_delim, "field_data or 'Invalid'")) + } + + // Leverage the FromStr implementation which now returns Self::Invalid on failure + fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> + where + E: ::serde::de::Error, + { + // parse() now returns Result<Self, Infallible> + // We unwrap() the Ok because it's infallible. + Ok(value.parse::<$enum_name>().unwrap()) + } + + fn visit_string<E>(self, value: String) -> Result<Self::Value, E> + where + E: ::serde::de::Error, + { + Ok(value.parse::<$enum_name>().unwrap()) + } + } + + deserializer.deserialize_str(EnumVisitor) + } + } + + // Implement Display + impl core::fmt::Display for $enum_name { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + $( + Self::$variant { $field } => { + write!(f, "{}{}{}", stringify!($variant), $tag_delim, $field) + } + )* + // Handle Invalid variant + Self::Invalid => write!(f, "Invalid"), + } + } + } + }; +} + +// --- Tests --- +#[cfg(test)] +mod tests { + #![allow(clippy::panic, clippy::expect_used)] + + use serde_json::{json, Value as JsonValue}; + + use crate::impl_enum_str; + + impl_enum_str!( + tag_delimeter = ":", + #[derive(Debug, PartialEq, Clone)] + pub enum TestEnum { + VariantA { value: i32 }, + VariantB { text: String }, + VariantC { id: u64 }, + VariantJson { data: JsonValue }, + } // Note: Invalid variant is added automatically by the macro + ); + + #[test] + fn test_enum_from_str_ok() { + // Success cases just parse directly + let parsed_a: TestEnum = "VariantA:42".parse().unwrap(); // Unwrapping Infallible is fine + assert_eq!(parsed_a, TestEnum::VariantA { value: 42 }); + + let parsed_b: TestEnum = "VariantB:hello world".parse().unwrap(); + assert_eq!( + parsed_b, + TestEnum::VariantB { + text: "hello world".to_string() + } + ); + + let parsed_c: TestEnum = "VariantC:123456789012345".parse().unwrap(); + assert_eq!( + parsed_c, + TestEnum::VariantC { + id: 123456789012345 + } + ); + + let parsed_json: TestEnum = r#"VariantJson:{"ok":true}"#.parse().unwrap(); + assert_eq!( + parsed_json, + TestEnum::VariantJson { + data: json!({"ok": true}) + } + ); + } + + #[test] + fn test_enum_from_str_failures_yield_invalid() { + // Missing delimiter + let parsed: TestEnum = "VariantA".parse().unwrap(); + assert_eq!(parsed, TestEnum::Invalid); + + // Unknown tag + let parsed: TestEnum = "UnknownVariant:123".parse().unwrap(); + assert_eq!(parsed, TestEnum::Invalid); + + // Bad field data for i32 + let parsed: TestEnum = "VariantA:not_a_number".parse().unwrap(); + assert_eq!(parsed, TestEnum::Invalid); + + // Bad field data for JsonValue + let parsed: TestEnum = r#"VariantJson:{"bad_json"#.parse().unwrap(); + assert_eq!(parsed, TestEnum::Invalid); + + // Empty field data for non-string (e.g., i32) + let parsed: TestEnum = "VariantA:".parse().unwrap(); + assert_eq!(parsed, TestEnum::Invalid); + + // Empty field data for string IS valid for String type + let parsed_str: TestEnum = "VariantB:".parse().unwrap(); + assert_eq!( + parsed_str, + TestEnum::VariantB { + text: "".to_string() + } + ); + + // Parsing the literal "Invalid" string + let parsed_invalid_str: TestEnum = "Invalid".parse().unwrap(); + assert_eq!(parsed_invalid_str, TestEnum::Invalid); + } + + #[test] + fn test_enum_display_and_serialize() { + // Display valid + let value_a = TestEnum::VariantA { value: 99 }; + assert_eq!(value_a.to_string(), "VariantA:99"); + // Serialize valid + let json_a = serde_json::to_string(&value_a).expect("Serialize A failed"); + assert_eq!(json_a, "\"VariantA:99\""); // Serializes to JSON string + + // Display Invalid + let value_invalid = TestEnum::Invalid; + assert_eq!(value_invalid.to_string(), "Invalid"); + // Serialize Invalid + let json_invalid = serde_json::to_string(&value_invalid).expect("Serialize Invalid failed"); + assert_eq!(json_invalid, "\"Invalid\""); // Serializes to JSON string "Invalid" + } + + #[test] + fn test_enum_deserialize() { + // Deserialize valid + let input_a = "\"VariantA:123\""; + let deserialized_a: TestEnum = serde_json::from_str(input_a).expect("Deserialize A failed"); + assert_eq!(deserialized_a, TestEnum::VariantA { value: 123 }); + + // Deserialize explicit "Invalid" + let input_invalid = "\"Invalid\""; + let deserialized_invalid: TestEnum = + serde_json::from_str(input_invalid).expect("Deserialize Invalid failed"); + assert_eq!(deserialized_invalid, TestEnum::Invalid); + + // Deserialize malformed string (according to macro rules) -> Invalid + let input_malformed = "\"VariantA_no_delimiter\""; + let deserialized_malformed: TestEnum = + serde_json::from_str(input_malformed).expect("Deserialize malformed should succeed"); + assert_eq!(deserialized_malformed, TestEnum::Invalid); + + // Deserialize string with bad field data -> Invalid + let input_bad_data = "\"VariantA:not_a_number\""; + let deserialized_bad_data: TestEnum = + serde_json::from_str(input_bad_data).expect("Deserialize bad data should succeed"); + assert_eq!(deserialized_bad_data, TestEnum::Invalid); + } +} diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 4b24cf281cb..e2cc195fe05 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -49,6 +49,7 @@ use crate::{ }, errors::{CustomResult, ParsingError, PercentageError, ValidationError}, fp_utils::when, + impl_enum_str, }; /// Represents Percentage Value between 0 and 100 both inclusive @@ -1348,3 +1349,22 @@ where self.0.to_sql(out) } } + +impl_enum_str!( + tag_delimeter = ":", + /// CreatedBy conveys the information about the creator (identifier) as well as the origin or + /// trigger (Api, Jwt) of the record. + #[derive(Eq, PartialEq, Debug, Clone)] + pub enum CreatedBy { + /// Api variant + Api { + /// merchant id of creator. + merchant_id: String, + }, + /// Jwt variant + Jwt { + /// user id of creator. + user_id: String, + }, + } +); diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 63f039c32f9..0a3c44deee1 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -89,6 +89,8 @@ pub struct PaymentAttempt { pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<storage_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, + pub processor_merchant_id: Option<id_type::MerchantId>, + pub created_by: Option<String>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, pub payment_method_subtype: storage_enums::PaymentMethodType, @@ -197,6 +199,8 @@ pub struct PaymentAttempt { pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub issuer_error_code: Option<String>, pub issuer_error_message: Option<String>, + pub processor_merchant_id: Option<id_type::MerchantId>, + pub created_by: Option<String>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, } @@ -334,6 +338,8 @@ pub struct PaymentAttemptNew { pub network_decline_code: Option<String>, pub network_advice_code: Option<String>, pub network_error_message: Option<String>, + pub processor_merchant_id: Option<id_type::MerchantId>, + pub created_by: Option<String>, } #[cfg(feature = "v1")] @@ -411,6 +417,8 @@ pub struct PaymentAttemptNew { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<storage_enums::CardDiscovery>, + pub processor_merchant_id: Option<id_type::MerchantId>, + pub created_by: Option<String>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, } diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 7476639a47d..840c8e085b9 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -60,6 +60,8 @@ pub struct PaymentIntent { pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, + pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, + pub created_by: Option<String>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, @@ -148,6 +150,8 @@ pub struct PaymentIntent { pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, + pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, + pub created_by: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)] @@ -337,6 +341,8 @@ pub struct PaymentIntentNew { pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, + pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, + pub created_by: Option<String>, } #[cfg(feature = "v1")] @@ -408,6 +414,8 @@ pub struct PaymentIntentNew { pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, + pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, + pub created_by: Option<String>, } #[cfg(feature = "v2")] diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 802aa698a82..374b341a47e 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -933,6 +933,10 @@ diesel::table! { #[max_length = 64] issuer_error_code -> Nullable<Varchar>, issuer_error_message -> Nullable<Text>, + #[max_length = 64] + processor_merchant_id -> Nullable<Varchar>, + #[max_length = 255] + created_by -> Nullable<Varchar>, setup_future_usage_applied -> Nullable<FutureUsage>, } } @@ -1021,6 +1025,10 @@ diesel::table! { platform_merchant_id -> Nullable<Varchar>, force_3ds_challenge -> Nullable<Bool>, force_3ds_challenge_trigger -> Nullable<Bool>, + #[max_length = 64] + processor_merchant_id -> Nullable<Varchar>, + #[max_length = 255] + created_by -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index b9ca1c5da46..9a72f663e4f 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -874,6 +874,10 @@ diesel::table! { capture_before -> Nullable<Timestamp>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, + #[max_length = 64] + processor_merchant_id -> Nullable<Varchar>, + #[max_length = 255] + created_by -> Nullable<Varchar>, payment_method_type_v2 -> Varchar, #[max_length = 128] connector_payment_id -> Nullable<Varchar>, @@ -954,6 +958,10 @@ diesel::table! { force_3ds_challenge -> Nullable<Bool>, force_3ds_challenge_trigger -> Nullable<Bool>, #[max_length = 64] + processor_merchant_id -> Nullable<Varchar>, + #[max_length = 255] + created_by -> Nullable<Varchar>, + #[max_length = 64] merchant_reference_id -> Nullable<Varchar>, billing_address -> Nullable<Bytea>, shipping_address -> Nullable<Bytea>, diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index 9212d416cb7..3779877abcb 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -210,6 +210,8 @@ pub struct PaymentAttemptBatchNew { pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, + pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, + pub created_by: Option<String>, pub setup_future_usage_applied: Option<common_enums::FutureUsage>, } @@ -293,6 +295,8 @@ impl PaymentAttemptBatchNew { extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, card_discovery: self.card_discovery, + processor_merchant_id: self.processor_merchant_id, + created_by: self.created_by, setup_future_usage_applied: self.setup_future_usage_applied, } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 90ba708c109..35b9f4a4613 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -15,7 +15,7 @@ use common_utils::{ errors::CustomResult, ext_traits::ValueExt, id_type, pii, - types::{keymanager::ToEncryptable, MinorUnit}, + types::{keymanager::ToEncryptable, CreatedBy, MinorUnit}, }; use diesel_models::payment_intent::TaxDetails; #[cfg(feature = "v2")] @@ -115,7 +115,8 @@ pub struct PaymentIntent { pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, - pub platform_merchant_id: Option<id_type::MerchantId>, + pub processor_merchant_id: id_type::MerchantId, + pub created_by: Option<CreatedBy>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, } @@ -493,13 +494,15 @@ pub struct PaymentIntent { pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>, /// The straight through routing algorithm id that is used for this payment. This overrides the default routing algorithm that is configured in business profile. pub routing_algorithm_id: Option<id_type::RoutingId>, - /// Identifier for the platform merchant. - pub platform_merchant_id: Option<id_type::MerchantId>, /// Split Payment Data pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, + /// merchant who owns the credentials of the processor, i.e. processor owner + pub processor_merchant_id: id_type::MerchantId, + /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) + pub created_by: Option<CreatedBy>, } #[cfg(feature = "v2")] @@ -655,11 +658,11 @@ impl PaymentIntent { .payment_link_config .map(ApiModelToDieselModelConvertor::convert_from), routing_algorithm_id: request.routing_algorithm_id, - platform_merchant_id: platform_merchant_id - .map(|merchant_account| merchant_account.get_id().to_owned()), split_payments: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, + processor_merchant_id: merchant_account.get_id().clone(), + created_by: None, }) } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index a074cca9b5d..77183dcf0d7 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -15,7 +15,7 @@ use common_utils::{ id_type, pii, types::{ keymanager::{self, KeyManagerState}, - ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit, + ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy, MinorUnit, }, }; use diesel_models::{ @@ -454,6 +454,10 @@ pub struct PaymentAttempt { pub charges: Option<common_types::payments::ConnectorChargeResponseData>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, + /// merchant who owns the credentials of the processor, i.e. processor owner + pub processor_merchant_id: id_type::MerchantId, + /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) + pub created_by: Option<CreatedBy>, } impl PaymentAttempt { @@ -583,6 +587,8 @@ impl PaymentAttempt { id, card_discovery: None, feature_metadata: None, + processor_merchant_id: payment_intent.merchant_id.clone(), + created_by: None, }) } @@ -670,6 +676,8 @@ impl PaymentAttempt { feature_metadata: None, id, card_discovery: None, + processor_merchant_id: payment_intent.merchant_id.clone(), + created_by: None, }) } @@ -767,6 +775,8 @@ impl PaymentAttempt { }), card_discovery: None, charges: None, + processor_merchant_id: payment_intent.merchant_id.clone(), + created_by: None, }) } @@ -859,6 +869,10 @@ pub struct PaymentAttempt { pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub issuer_error_code: Option<String>, pub issuer_error_message: Option<String>, + /// merchant who owns the credentials of the processor, i.e. processor owner + pub processor_merchant_id: id_type::MerchantId, + /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) + pub created_by: Option<CreatedBy>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, } @@ -1109,6 +1123,10 @@ pub struct PaymentAttemptNew { pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, + /// merchant who owns the credentials of the processor, i.e. processor owner + pub processor_merchant_id: id_type::MerchantId, + /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) + pub created_by: Option<CreatedBy>, pub setup_future_usage_applied: Option<storage_enums::FutureUsage>, } @@ -1859,6 +1877,8 @@ impl behaviour::Conversion for PaymentAttempt { setup_future_usage_applied: self.setup_future_usage_applied, // Below fields are deprecated. Please add any new fields above this line. connector_transaction_data: None, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|cb| cb.to_string()), }) } @@ -1877,7 +1897,7 @@ impl behaviour::Conversion for PaymentAttempt { .cloned(); Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, - merchant_id: storage_model.merchant_id, + merchant_id: storage_model.merchant_id.clone(), attempt_id: storage_model.attempt_id, status: storage_model.status, net_amount: NetAmount::new( @@ -1947,6 +1967,12 @@ impl behaviour::Conversion for PaymentAttempt { charges: storage_model.charges, issuer_error_code: storage_model.issuer_error_code, issuer_error_message: storage_model.issuer_error_message, + processor_merchant_id: storage_model + .processor_merchant_id + .unwrap_or(storage_model.merchant_id), + created_by: storage_model + .created_by + .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), setup_future_usage_applied: storage_model.setup_future_usage_applied, }) } @@ -2033,6 +2059,8 @@ impl behaviour::Conversion for PaymentAttempt { extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, card_discovery: self.card_discovery, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|cb| cb.to_string()), setup_future_usage_applied: self.setup_future_usage_applied, }) } @@ -2103,6 +2131,8 @@ impl behaviour::Conversion for PaymentAttempt { card_discovery, charges, feature_metadata, + processor_merchant_id, + created_by, } = self; let AttemptAmountDetails { @@ -2195,6 +2225,8 @@ impl behaviour::Conversion for PaymentAttempt { network_error_message: error .as_ref() .and_then(|details| details.network_error_message.clone()), + processor_merchant_id: Some(processor_merchant_id), + created_by: created_by.map(|cb| cb.to_string()), }) } @@ -2266,7 +2298,7 @@ impl behaviour::Conversion for PaymentAttempt { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, - merchant_id: storage_model.merchant_id, + merchant_id: storage_model.merchant_id.clone(), id: storage_model.id, status: storage_model.status, amount_details, @@ -2311,6 +2343,12 @@ impl behaviour::Conversion for PaymentAttempt { connector_token_details: storage_model.connector_token_details, card_discovery: storage_model.card_discovery, feature_metadata: storage_model.feature_metadata.map(From::from), + processor_merchant_id: storage_model + .processor_merchant_id + .unwrap_or(storage_model.merchant_id), + created_by: storage_model + .created_by + .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), }) } .await @@ -2367,6 +2405,8 @@ impl behaviour::Conversion for PaymentAttempt { card_discovery, charges, feature_metadata, + processor_merchant_id, + created_by, } = self; let card_network = payment_method_data @@ -2456,6 +2496,8 @@ impl behaviour::Conversion for PaymentAttempt { network_error_message: error_details .as_ref() .and_then(|details| details.network_error_message.clone()), + processor_merchant_id: Some(processor_merchant_id), + created_by: created_by.map(|cb| cb.to_string()), }) } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index a55b1b62fab..de2e0dd46c9 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -14,7 +14,7 @@ use common_utils::{ type_name, types::{ keymanager::{self, KeyManagerState, ToEncryptable}, - MinorUnit, + CreatedBy, MinorUnit, }, }; #[cfg(feature = "v2")] @@ -1602,10 +1602,11 @@ impl behaviour::Conversion for PaymentIntent { customer_present, routing_algorithm_id, payment_link_config, - platform_merchant_id, split_payments, force_3ds_challenge, force_3ds_challenge_trigger, + processor_merchant_id, + created_by, } = self; Ok(DieselPaymentIntent { skip_external_tax_calculation: Some(amount_details.get_external_tax_action_as_bool()), @@ -1684,10 +1685,12 @@ impl behaviour::Conversion for PaymentIntent { routing_algorithm_id, psd2_sca_exemption_type: None, request_extended_authorization: None, - platform_merchant_id, + platform_merchant_id: None, split_payments, force_3ds_challenge, force_3ds_challenge_trigger, + processor_merchant_id: Some(processor_merchant_id), + created_by: created_by.map(|cb| cb.to_string()), }) } async fn convert_back( @@ -1761,7 +1764,7 @@ impl behaviour::Conversion for PaymentIntent { .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed)?; Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - merchant_id: storage_model.merchant_id, + merchant_id: storage_model.merchant_id.clone(), status: storage_model.status, amount_details, amount_captured: storage_model.amount_captured, @@ -1819,10 +1822,15 @@ impl behaviour::Conversion for PaymentIntent { customer_present: storage_model.customer_present.into(), payment_link_config: storage_model.payment_link_config, routing_algorithm_id: storage_model.routing_algorithm_id, - platform_merchant_id: storage_model.platform_merchant_id, split_payments: storage_model.split_payments, force_3ds_challenge: storage_model.force_3ds_challenge, force_3ds_challenge_trigger: storage_model.force_3ds_challenge_trigger, + processor_merchant_id: storage_model + .processor_merchant_id + .unwrap_or(storage_model.merchant_id), + created_by: storage_model + .created_by + .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), }) } .await @@ -1903,9 +1911,11 @@ impl behaviour::Conversion for PaymentIntent { tax_details: amount_details.tax_details, enable_payment_link: Some(self.enable_payment_link.as_bool()), apply_mit_exemption: Some(self.apply_mit_exemption.as_bool()), - platform_merchant_id: self.platform_merchant_id, + platform_merchant_id: None, force_3ds_challenge: self.force_3ds_challenge, force_3ds_challenge_trigger: self.force_3ds_challenge_trigger, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|cb| cb.to_string()), }) } } @@ -1973,7 +1983,9 @@ impl behaviour::Conversion for PaymentIntent { skip_external_tax_calculation: self.skip_external_tax_calculation, request_extended_authorization: self.request_extended_authorization, psd2_sca_exemption_type: self.psd2_sca_exemption_type, - platform_merchant_id: self.platform_merchant_id, + platform_merchant_id: None, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|cb| cb.to_string()), force_3ds_challenge: self.force_3ds_challenge, force_3ds_challenge_trigger: self.force_3ds_challenge_trigger, }) @@ -2011,7 +2023,7 @@ impl behaviour::Conversion for PaymentIntent { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, - merchant_id: storage_model.merchant_id, + merchant_id: storage_model.merchant_id.clone(), status: storage_model.status, amount: storage_model.amount, currency: storage_model.currency, @@ -2065,7 +2077,12 @@ impl behaviour::Conversion for PaymentIntent { skip_external_tax_calculation: storage_model.skip_external_tax_calculation, request_extended_authorization: storage_model.request_extended_authorization, psd2_sca_exemption_type: storage_model.psd2_sca_exemption_type, - platform_merchant_id: storage_model.platform_merchant_id, + processor_merchant_id: storage_model + .processor_merchant_id + .unwrap_or(storage_model.merchant_id), + created_by: storage_model + .created_by + .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), force_3ds_challenge: storage_model.force_3ds_challenge, force_3ds_challenge_trigger: storage_model.force_3ds_challenge_trigger, }) @@ -2133,7 +2150,9 @@ impl behaviour::Conversion for PaymentIntent { skip_external_tax_calculation: self.skip_external_tax_calculation, request_extended_authorization: self.request_extended_authorization, psd2_sca_exemption_type: self.psd2_sca_exemption_type, - platform_merchant_id: self.platform_merchant_id, + platform_merchant_id: None, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|cb| cb.to_string()), force_3ds_challenge: self.force_3ds_challenge, force_3ds_challenge_trigger: self.force_3ds_challenge_trigger, }) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 6953d1837d1..9d29c9ffaa4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3816,7 +3816,8 @@ mod tests { skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, - platform_merchant_id: None, + processor_merchant_id: id_type::MerchantId::default(), + created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, }; @@ -3890,7 +3891,8 @@ mod tests { skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, - platform_merchant_id: None, + processor_merchant_id: id_type::MerchantId::default(), + created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, }; @@ -3962,7 +3964,8 @@ mod tests { skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, - platform_merchant_id: None, + processor_merchant_id: id_type::MerchantId::default(), + created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, }; @@ -4500,6 +4503,8 @@ impl AttemptType { extended_authorization_applied: None, capture_before: None, card_discovery: None, + processor_merchant_id: old_payment_attempt.processor_merchant_id, + created_by: old_payment_attempt.created_by, setup_future_usage_applied: None, } } diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index c5837d5435b..377b930a572 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -11,7 +11,6 @@ use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentData}, - utils::ValidatePlatformMerchant, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, @@ -46,7 +45,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, - platform_merchant_account: Option<&domain::MerchantAccount>, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest, PaymentData<F>>, > { @@ -71,9 +70,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[IntentStatus::Failed, IntentStatus::Succeeded], diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 46ae753232f..9d4ff7a5579 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -12,7 +12,6 @@ use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentData}, - utils::ValidatePlatformMerchant, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, @@ -47,7 +46,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, - platform_merchant_account: Option<&domain::MerchantAccount>, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsCancelRequest, PaymentData<F>>, > { @@ -71,9 +70,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 2bde0d54976..68100cb6ece 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -11,7 +11,6 @@ use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations, types::MultipleCaptureData}, - utils::ValidatePlatformMerchant, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, @@ -46,7 +45,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, - platform_merchant_account: Option<&domain::MerchantAccount>, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse< 'a, @@ -77,9 +76,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, diff --git a/crates/router/src/core/payments/operations/payment_capture_v2.rs b/crates/router/src/core/payments/operations/payment_capture_v2.rs index f69dd8de62c..4f9f9d31224 100644 --- a/crates/router/src/core/payments/operations/payment_capture_v2.rs +++ b/crates/router/src/core/payments/operations/payment_capture_v2.rs @@ -12,7 +12,6 @@ use crate::{ helpers, operations::{self, ValidateStatusForOperation}, }, - utils::ValidatePlatformMerchant, }, routes::{app::ReqState, SessionState}, types::{ @@ -158,9 +157,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentCaptureData<F>, PaymentsCaptureReques .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - self.validate_status_for_operation(payment_intent.status)?; let active_attempt_id = payment_intent diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index ef90a2f2bef..bc7d743e3f8 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -1366,6 +1366,8 @@ impl PaymentCreate { extended_authorization_applied: None, capture_before: None, card_discovery: None, + processor_merchant_id: merchant_id.to_owned(), + created_by: None, setup_future_usage_applied: request.setup_future_usage, }, additional_pm_data, @@ -1388,7 +1390,7 @@ impl PaymentCreate { active_attempt_id: String, profile_id: common_utils::id_type::ProfileId, session_expiry: PrimitiveDateTime, - platform_merchant_account: Option<&domain::MerchantAccount>, + _platform_merchant_account: Option<&domain::MerchantAccount>, business_profile: &domain::Profile, ) -> RouterResult<storage::PaymentIntent> { let created_at @ modified_at @ last_synced = common_utils::date_time::now(); @@ -1580,8 +1582,8 @@ impl PaymentCreate { skip_external_tax_calculation, request_extended_authorization: request.request_extended_authorization, psd2_sca_exemption_type: request.psd2_sca_exemption_type, - platform_merchant_id: platform_merchant_account - .map(|platform_merchant_account| platform_merchant_account.get_id().to_owned()), + processor_merchant_id: merchant_account.get_id().to_owned(), + created_by: None, force_3ds_challenge: request.force_3ds_challenge, force_3ds_challenge_trigger: Some(force_3ds_challenge_trigger), }) diff --git a/crates/router/src/core/payments/operations/payment_get.rs b/crates/router/src/core/payments/operations/payment_get.rs index f15990d67b9..7e23cf6f84d 100644 --- a/crates/router/src/core/payments/operations/payment_get.rs +++ b/crates/router/src/core/payments/operations/payment_get.rs @@ -13,7 +13,6 @@ use crate::{ helpers, operations::{self, ValidateStatusForOperation}, }, - utils::ValidatePlatformMerchant, }, routes::{app::ReqState, SessionState}, types::{ @@ -135,9 +134,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentStatusData<F>, PaymentsRetriev .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - let payment_attempt = payment_intent .active_attempt_id .as_ref() diff --git a/crates/router/src/core/payments/operations/payment_get_intent.rs b/crates/router/src/core/payments/operations/payment_get_intent.rs index 2e00b19c757..764fa937c23 100644 --- a/crates/router/src/core/payments/operations/payment_get_intent.rs +++ b/crates/router/src/core/payments/operations/payment_get_intent.rs @@ -10,7 +10,6 @@ use crate::{ core::{ errors::{self, RouterResult}, payments::{self, helpers, operations}, - utils::ValidatePlatformMerchant, }, db::errors::StorageErrorExt, routes::{app::ReqState, SessionState}, @@ -100,9 +99,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 82f09fc2075..0a230c3d110 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -11,7 +11,6 @@ use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{helpers, operations, PaymentAddress, PaymentData}, - utils::ValidatePlatformMerchant, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, @@ -44,7 +43,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, - platform_merchant_account: Option<&domain::MerchantAccount>, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>> { let db = &*state.store; @@ -67,9 +66,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 5b5155bbe33..aab887b2c03 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -218,7 +218,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieve ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>, > { - get_tracker_for_sync( + Box::pin(get_tracker_for_sync( payment_id, merchant_account, key_store, @@ -227,7 +227,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieve self, merchant_account.storage_scheme, platform_merchant_account, - ) + )) .await } } diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs index 5a283409edf..711115292ac 100644 --- a/crates/router/src/core/payments/operations/payment_update_intent.rs +++ b/crates/router/src/core/payments/operations/payment_update_intent.rs @@ -27,7 +27,6 @@ use crate::{ self, helpers, operations::{self, ValidateStatusForOperation}, }, - utils::ValidatePlatformMerchant, }, db::errors::StorageErrorExt, routes::{app::ReqState, SessionState}, @@ -150,9 +149,6 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpda .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - self.validate_status_for_operation(payment_intent.status)?; let PaymentsUpdateIntentRequest { diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index dc87ca9140c..dfec91875a9 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -15,7 +15,6 @@ use crate::{ self, helpers, operations, CustomerDetails, IncrementalAuthorizationDetails, PaymentAddress, }, - utils::ValidatePlatformMerchant, }, routes::{app::ReqState, SessionState}, services, @@ -49,7 +48,7 @@ impl<F: Send + Clone + Sync> key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, - platform_merchant_account: Option<&domain::MerchantAccount>, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse< 'a, @@ -78,9 +77,6 @@ impl<F: Send + Clone + Sync> .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent - .validate_platform_merchant(platform_merchant_account.map(|ma| ma.get_id()))?; - helpers::validate_payment_status_against_allowed_statuses( payment_intent.status, &[enums::IntentStatus::RequiresCapture], diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 9e179d55524..fb907a0f282 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -685,6 +685,8 @@ pub fn make_new_payment_attempt( extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: old_payment_attempt.card_discovery, + processor_merchant_id: old_payment_attempt.processor_merchant_id, + created_by: old_payment_attempt.created_by, setup_future_usage_applied: setup_futture_usage_intent, // setup future usage is picked from intent for new payment attempt } } diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 87dce4ade0b..36e7423da18 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -1837,36 +1837,3 @@ pub(crate) fn validate_profile_id_from_auth_layer<T: GetProfileId + std::fmt::De (None, None) | (None, Some(_)) => Ok(()), } } - -pub(crate) trait ValidatePlatformMerchant { - fn get_platform_merchant_id(&self) -> Option<&common_utils::id_type::MerchantId>; - - fn validate_platform_merchant( - &self, - auth_platform_merchant_id: Option<&common_utils::id_type::MerchantId>, - ) -> CustomResult<(), errors::ApiErrorResponse> { - let data_platform_merchant_id = self.get_platform_merchant_id(); - match (data_platform_merchant_id, auth_platform_merchant_id) { - (Some(data_platform_merchant_id), Some(auth_platform_merchant_id)) => { - common_utils::fp_utils::when( - data_platform_merchant_id != auth_platform_merchant_id, - || { - Err(report!(errors::ApiErrorResponse::PaymentNotFound)).attach_printable(format!( - "Data platform merchant id: {data_platform_merchant_id:?} does not match with auth platform merchant id: {auth_platform_merchant_id:?}")) - }, - ) - } - (Some(_), None) | (None, Some(_)) => { - Err(report!(errors::ApiErrorResponse::InvalidPlatformOperation)) - .attach_printable("Platform merchant id is missing in either data or auth") - } - (None, None) => Ok(()), - } - } -} - -impl ValidatePlatformMerchant for storage::PaymentIntent { - fn get_platform_merchant_id(&self) -> Option<&common_utils::id_type::MerchantId> { - self.platform_merchant_id.as_ref() - } -} diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index b2ef401abcf..3a942f70e32 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -222,6 +222,8 @@ mod tests { extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), + processor_merchant_id: Default::default(), + created_by: None, setup_future_usage_applied: Default::default(), }; @@ -310,6 +312,8 @@ mod tests { extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), + processor_merchant_id: Default::default(), + created_by: None, setup_future_usage_applied: Default::default(), }; let store = state @@ -411,6 +415,8 @@ mod tests { extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), + processor_merchant_id: Default::default(), + created_by: None, setup_future_usage_applied: Default::default(), }; let store = state diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index 3ec06e4cd91..4dceb77d58d 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -276,7 +276,8 @@ pub async fn generate_sample_data( skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, - platform_merchant_id: None, + processor_merchant_id: merchant_id.clone(), + created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, }; @@ -368,6 +369,8 @@ pub async fn generate_sample_data( extended_authorization_applied: None, capture_before: None, card_discovery: None, + processor_merchant_id: Some(merchant_id.clone()), + created_by: None, setup_future_usage_applied: None, }; diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 1b97970bf16..5ce1c8b7b54 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -232,6 +232,8 @@ impl PaymentAttemptInterface for MockDb { charges: None, issuer_error_code: None, issuer_error_message: None, + processor_merchant_id: payment_attempt.processor_merchant_id, + created_by: payment_attempt.created_by, setup_future_usage_applied: payment_attempt.setup_future_usage_applied, }; payment_attempts.push(payment_attempt.clone()); diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 25d89cbd6eb..98a7a62dc6b 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -3,7 +3,7 @@ use common_utils::types::keymanager::KeyManagerState; use common_utils::{ errors::CustomResult, fallback_reverse_lookup_not_found, - types::{ConnectorTransactionId, ConnectorTransactionIdTrait}, + types::{ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy}, }; use diesel_models::{ enums::{ @@ -650,6 +650,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { charges: None, issuer_error_code: None, issuer_error_message: None, + processor_merchant_id: payment_attempt.processor_merchant_id.clone(), + created_by: payment_attempt.created_by.clone(), setup_future_usage_applied: payment_attempt.setup_future_usage_applied, }; @@ -1657,6 +1659,8 @@ impl DataModelExt for PaymentAttempt { setup_future_usage_applied: self.setup_future_usage_applied, // Below fields are deprecated. Please add any new fields above this line. connector_transaction_data: None, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|created_by| created_by.to_string()), } } @@ -1673,7 +1677,7 @@ impl DataModelExt for PaymentAttempt { storage_model.tax_amount, ), payment_id: storage_model.payment_id, - merchant_id: storage_model.merchant_id, + merchant_id: storage_model.merchant_id.clone(), attempt_id: storage_model.attempt_id, status: storage_model.status, currency: storage_model.currency, @@ -1740,6 +1744,12 @@ impl DataModelExt for PaymentAttempt { charges: storage_model.charges, issuer_error_code: storage_model.issuer_error_code, issuer_error_message: storage_model.issuer_error_message, + processor_merchant_id: storage_model + .processor_merchant_id + .unwrap_or(storage_model.merchant_id), + created_by: storage_model + .created_by + .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), setup_future_usage_applied: storage_model.setup_future_usage_applied, } } @@ -1827,6 +1837,8 @@ impl DataModelExt for PaymentAttemptNew { extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, card_discovery: self.card_discovery, + processor_merchant_id: Some(self.processor_merchant_id), + created_by: self.created_by.map(|created_by| created_by.to_string()), setup_future_usage_applied: self.setup_future_usage_applied, } } @@ -1841,7 +1853,7 @@ impl DataModelExt for PaymentAttemptNew { storage_model.tax_amount, ), payment_id: storage_model.payment_id, - merchant_id: storage_model.merchant_id, + merchant_id: storage_model.merchant_id.clone(), attempt_id: storage_model.attempt_id, status: storage_model.status, currency: storage_model.currency, @@ -1903,6 +1915,12 @@ impl DataModelExt for PaymentAttemptNew { extended_authorization_applied: storage_model.extended_authorization_applied, capture_before: storage_model.capture_before, card_discovery: storage_model.card_discovery, + processor_merchant_id: storage_model + .processor_merchant_id + .unwrap_or(storage_model.merchant_id), + created_by: storage_model + .created_by + .and_then(|created_by| created_by.parse::<CreatedBy>().ok()), setup_future_usage_applied: storage_model.setup_future_usage_applied, } } diff --git a/migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/down.sql b/migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/down.sql new file mode 100644 index 00000000000..f56ae9f5ef5 --- /dev/null +++ b/migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/down.sql @@ -0,0 +1,5 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent DROP COLUMN IF EXISTS processor_merchant_id; +ALTER TABLE payment_intent DROP COLUMN IF EXISTS created_by; +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS processor_merchant_id; +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS created_by; diff --git a/migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/up.sql b/migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/up.sql new file mode 100644 index 00000000000..52932564b4b --- /dev/null +++ b/migrations/2025-03-21-091838_add_new_col_processor_mid_and_created_by/up.sql @@ -0,0 +1,8 @@ +-- Your SQL goes here +ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS processor_merchant_id VARCHAR(64); +ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS created_by VARCHAR(255); +ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS processor_merchant_id VARCHAR(64); +ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS created_by VARCHAR(255); +-- This backfill should be executed again after deployment. +UPDATE payment_intent SET processor_merchant_id = merchant_id where processor_merchant_id IS NULL; +UPDATE payment_attempt SET processor_merchant_id = merchant_id where processor_merchant_id IS NULL;
2025-04-08T14:40:56Z
## 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 --> - added `processor_merchant_id` and` created_by` column in `diesel_models` and `hyperswitch_domain_models` - added migrations - ~added backfilling `processor_merchant_id` column in migrations~ (Due to staggered release backfilling should be done at a later point after deployment is complete so it can't be done in the scope of this PR) - populating these fields with default scenario values as mentions in [Motivation and Context](#motivation-and-context) - removing `platform_merchant_id` column and population instances from `hyperswitch_domain_models`. - created a macro `impl_enum_str!` to implement serialization and deserialization for any enum with singleton associated data. - for e.g ```rust CreatedBy::Api { merchant_id: merchant_32423 } ``` will be serialized to `Api:merchant_32423` ### 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). --> Fixes #7769 #### Introducing two fields in payment_intent and payment_attempt table namely, - `processor_merchant_id` - `created_by` #### Terminology | column | description | | ----------| -------- | | **merchant_id**(already exists) | Who actually configures payment settings, or who has integrated with us, i.e **owner**. | | **processor_merchant_id** | Who owns the credentials of the processor, i.e. processor owner | | **created_by** | who invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) | #### Value combination matrix | Cases | merchant_id | processor_merchant_id | created_by(null) | | --------------------------------------------------- | ----------- | --------------------- | -----------| | Normal (non vsas) | 123 | 123 | 123 | | Platform performing for connected | pid1 | 123 | pid1 | | Platform performing for platform | pid1 | pid1 | pid1 | | Connected making some operation on top of a payment | pid1 | 123 | 123 | >created_by is an enum struct ```rust pub enum CreatedBy { Api { merchant_id: id_type::MerchantId }, Jwt { user_id: String }, } ``` #### **Important Note**: This PR is just a scaffold for the next changes to come that will include several logic like, determining what scenario it is mentioned in the above table and populating column fields accordingly. ## 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)? --> ### Steps 1. Make a payment ```sh curl --location '{{baseurl}}/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ****redacted****' \ --data-raw '{ "amount": 104000, "currency": "GBP", "amount_to_capture": 104000, "confirm": true, "profile_id": "**redacted**", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "routing": { "type": "single", "data": "stripe" }, "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "re", "card_exp_month": "01", "card_exp_year": "99", "card_holder_name": "John Smith", "card_cvc": "257" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 104000, "account_name": "transaction_processing" } ], "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal", "request_incremental_authorization": false, "merchant_order_reference_id": "test_ord", "session_expiry": 900 }' ``` response ```json { "payment_id": "pay_mzSYO8ZS6YgxJ8qhpk10", "merchant_id": "merchant_1744876813", "status": "processing", "amount": 104000, "net_amount": 104000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "checkout", "client_secret": "****redacted****", "created": "2025-04-17T08:11:05.286Z", "currency": "GBP", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0131", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "453243", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "99", "card_holder_name": "John Smith", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 104000, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": "John Doe", "phone": "9999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1744877465, "expires": 1744881065, "secret": "****redacted****" }, "manual_retry_allowed": false, "connector_transaction_id": "pay_smcaidph7qhefdvm653lrn6wda", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" }, "braintree": null }, "feature_metadata": null, "reference_id": "pay_mzSYO8ZS6YgxJ8qhpk10_1", "payment_link": null, "profile_id": "pro_RZojFbEiPLcW3fj9rK1W", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_J1wam8mC5wvSWgcWAoiz", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-17T08:26:05.286Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-17T08:11:06.465Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "test_ord", "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` 2. run the sql query in psql console ```sql select merchant_id, processor_merchant_id, created_by from payment_intent; ``` run the above query ### Result | merchant_id | processor_merchant_id | created_by| | --------------------- | ----------------------- | ------------------------- | | merchant_1 | merchant_1 | | | merchant_2 | merchant_2 | | ## 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.113.0
103a5c182b9744faf27d367efd58fac669d5c2ba
103a5c182b9744faf27d367efd58fac669d5c2ba
juspay/hyperswitch
juspay__hyperswitch-7755
Bug: [CI] cypress checks for wise failing wise is returning status as `forbidden`. it is better to replace that with adyen payouts
2025-04-08T07:04:59Z
## 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 --> this pr updates the `adyen` payouts credentials and it also replaces wise from running in github ci ### 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). --> ci checks are failing across all prs. closes #7755 ## 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)? --> ci checks should pass. ## 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.113.0
de86066402fab0d7725f7ee71085862b3b8c74e9
de86066402fab0d7725f7ee71085862b3b8c74e9
juspay/hyperswitch
juspay__hyperswitch-7759
Bug: Create authentications to fallback to ApiKeyAuth if AdminApiAuth fails hotfix Create two new authentication mechanisms that enhance the existing AdminApiAuth and AdminApiAuthWithMerchantIdFromRoute by allowing fallback to regular API key-based authentication when the admin key check fails.
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index c59b8471344..7cd4ce2d4bd 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -480,6 +480,7 @@ pub(crate) async fn fetch_raw_secrets( #[cfg(feature = "olap")] replica_database, secrets, + fallback_merchant_ids_api_key_auth: conf.fallback_merchant_ids_api_key_auth, locker: conf.locker, connectors: conf.connectors, forex_api, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index a4c454ec196..83591b15e36 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -66,6 +66,7 @@ pub struct Settings<S: SecretState> { pub redis: RedisSettings, pub log: Log, pub secrets: SecretStateContainer<Secrets, S>, + pub fallback_merchant_ids_api_key_auth: Option<FallbackMerchantIds>, pub locker: Locker, pub key_manager: SecretStateContainer<KeyManagerConfig, S>, pub connectors: Connectors, @@ -676,6 +677,13 @@ pub struct Secrets { pub master_enc_key: Secret<String>, } +#[derive(Debug, Default, Deserialize, Clone)] +#[serde(default)] +pub struct FallbackMerchantIds { + #[serde(deserialize_with = "deserialize_merchant_ids")] + pub merchant_ids: HashSet<id_type::MerchantId>, +} + #[derive(Debug, Clone, Default, Deserialize)] pub struct UserSettings { pub password_validity_in_days: u16, @@ -1271,6 +1279,53 @@ where })? } +fn deserialize_merchant_ids_inner( + value: impl AsRef<str>, +) -> Result<HashSet<id_type::MerchantId>, String> { + let (values, errors) = value + .as_ref() + .trim() + .split(',') + .map(|s| { + let trimmed = s.trim(); + id_type::MerchantId::wrap(trimmed.to_owned()).map_err(|error| { + format!( + "Unable to deserialize `{}` as `MerchantId`: {error}", + trimmed + ) + }) + }) + .fold( + (HashSet::new(), Vec::new()), + |(mut values, mut errors), result| match result { + Ok(t) => { + values.insert(t); + (values, errors) + } + Err(error) => { + errors.push(error); + (values, errors) + } + }, + ); + + if !errors.is_empty() { + Err(format!("Some errors occurred:\n{}", errors.join("\n"))) + } else { + Ok(values) + } +} + +fn deserialize_merchant_ids<'de, D>( + deserializer: D, +) -> Result<HashSet<id_type::MerchantId>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let s = String::deserialize(deserializer)?; + deserialize_merchant_ids_inner(s).map_err(serde::de::Error::custom) +} + impl<'de> Deserialize<'de> for TenantConfig { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 1c494542228..2be9058e906 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -186,7 +186,7 @@ pub async fn merchant_account_create( &req, json_payload.into_inner(), |state, _, req, _| create_merchant_account(state, req), - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallback, api_locking::LockAction::NotApplicable, )) .await @@ -249,7 +249,7 @@ pub async fn retrieve_merchant_account( payload, |state, _, req, _| get_merchant_account(state, req, None), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be MerchantAccountRead, but since FE is calling this API for @@ -350,7 +350,7 @@ pub async fn merchant_account_list( query_params.into_inner(), |state, _, request, _| list_merchant_account(state, request), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallback, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountRead, }, @@ -409,7 +409,7 @@ pub async fn update_merchant_account( json_payload.into_inner(), |state, _, req, _| merchant_account_update(state, &merchant_id, None, req), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantAccountWrite, diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 911617753d4..087e295dc8e 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -29,7 +29,7 @@ pub async fn api_key_create( api_keys::create_api_key(state, payload, auth_data.key_store).await }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyWrite, @@ -130,7 +130,7 @@ pub async fn api_key_retrieve( (merchant_id.clone(), key_id.clone()), |state, _, (merchant_id, key_id), _| api_keys::retrieve_api_key(state, merchant_id, key_id), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyRead, @@ -166,7 +166,7 @@ pub async fn api_key_update( payload, |state, _, payload, _| api_keys::update_api_key(state, payload), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantApiKeyWrite, @@ -303,7 +303,7 @@ pub async fn api_key_list( api_keys::list_api_keys(state, merchant_id, limit, offset).await }, auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantApiKeyRead, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 7e3d6802b88..3b9fcfc0d8e 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -654,113 +654,20 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { - let merchant_id_from_route = self.0.clone(); - let api_key = get_api_key(request_headers) - .change_context(errors::ApiErrorResponse::Unauthorized)? - .trim(); - if api_key.is_empty() { - return Err(errors::ApiErrorResponse::Unauthorized) - .attach_printable("API key is empty"); - } - - let api_key = api_keys::PlaintextApiKey::from(api_key); - let hash_key = { - let config = state.conf(); - config.api_keys.get_inner().get_hash_key()? - }; - let hashed_api_key = api_key.keyed_hash(hash_key.peek()); - - let stored_api_key = state - .store() - .find_api_key_by_hash_optional(hashed_api_key.into()) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed - .attach_printable("Failed to retrieve API key")? - .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` - .attach_printable("Merchant not authenticated")?; - - if stored_api_key - .expires_at - .map(|expires_at| expires_at < date_time::now()) - .unwrap_or(false) - { - return Err(report!(errors::ApiErrorResponse::Unauthorized)) - .attach_printable("API key has expired"); - } - - let key_manager_state = &(&state.session_state()).into(); - - let key_store = state - .store() - .get_merchant_key_store_by_merchant_id( - key_manager_state, - &stored_api_key.merchant_id, - &state.store().get_master_key().to_vec().into(), - ) - .await - .change_context(errors::ApiErrorResponse::Unauthorized) - .attach_printable("Failed to fetch merchant key store for the merchant id")?; + let (auth_data, auth_type) = ApiKeyAuth + .authenticate_and_fetch(request_headers, state) + .await?; - let profile_id = - get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)? - .map(id_type::ProfileId::from_str) - .transpose() - .change_context(errors::ValidationError::IncorrectValueProvided { - field_name: "X-Profile-Id", - }) - .change_context(errors::ApiErrorResponse::Unauthorized)?; + let merchant_id_from_route = self.0.clone(); + let merchant_id_from_api_key = auth_data.merchant_account.get_id(); - if merchant_id_from_route != stored_api_key.merchant_id { + if merchant_id_from_route != *merchant_id_from_api_key { return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( "Merchant ID from route and Merchant ID from api-key in header do not match", ); } - let merchant = state - .store() - .find_merchant_account_by_merchant_id( - key_manager_state, - &stored_api_key.merchant_id, - &key_store, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; - - // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account - let (merchant, platform_merchant_account) = if state.conf().platform.enabled { - get_platform_merchant_account(state, request_headers, merchant).await? - } else { - (merchant, None) - }; - - let key_store = if platform_merchant_account.is_some() { - state - .store() - .get_merchant_key_store_by_merchant_id( - key_manager_state, - merchant.get_id(), - &state.store().get_master_key().to_vec().into(), - ) - .await - .change_context(errors::ApiErrorResponse::Unauthorized) - .attach_printable("Failed to fetch merchant key store for the merchant id")? - } else { - key_store - }; - - let auth = AuthenticationData { - merchant_account: merchant, - platform_merchant_account, - key_store, - profile_id, - }; - Ok(( - auth.clone(), - AuthenticationType::ApiKey { - merchant_id: auth.merchant_account.get_id().clone(), - key_id: stored_api_key.key_id, - }, - )) + Ok((auth_data, auth_type)) } } @@ -1398,6 +1305,198 @@ where } } +#[derive(Debug, Default)] +pub struct AdminApiAuthWithApiKeyFallback; + +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<(), A> for AdminApiAuthWithApiKeyFallback +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<((), AuthenticationType)> { + let request_api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + + let conf = state.conf(); + + let admin_api_key = &conf.secrets.get_inner().admin_api_key; + + if request_api_key == admin_api_key.peek() { + return Ok(((), AuthenticationType::AdminApiKey)); + } + let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else { + return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( + "Api Key Authentication Failure: fallback merchant set not configured", + ); + }; + + let api_key = api_keys::PlaintextApiKey::from(request_api_key); + let hash_key = conf.api_keys.get_inner().get_hash_key()?; + let hashed_api_key = api_key.keyed_hash(hash_key.peek()); + + let stored_api_key = state + .store() + .find_api_key_by_hash_optional(hashed_api_key.into()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve API key")? + .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) + .attach_printable("Merchant not authenticated")?; + + if stored_api_key + .expires_at + .map(|expires_at| expires_at < date_time::now()) + .unwrap_or(false) + { + return Err(report!(errors::ApiErrorResponse::Unauthorized)) + .attach_printable("API key has expired"); + } + + if fallback_merchant_ids + .merchant_ids + .contains(&stored_api_key.merchant_id) + { + return Ok(( + (), + AuthenticationType::ApiKey { + merchant_id: stored_api_key.merchant_id, + key_id: stored_api_key.key_id, + }, + )); + } + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Authentication Failure")) + } +} + +#[derive(Debug, Default)] +pub struct AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(pub id_type::MerchantId); + +#[cfg(feature = "v1")] +impl AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute { + async fn fetch_merchant_key_store_and_account<A: SessionStateInfo + Sync>( + merchant_id: &id_type::MerchantId, + state: &A, + ) -> RouterResult<(domain::MerchantKeyStore, domain::MerchantAccount)> { + let key_manager_state = &(&state.session_state()).into(); + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + let merchant = state + .store() + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + Ok((key_store, merchant)) + } +} + +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> + for AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let merchant_id_from_route: id_type::MerchantId = self.0.clone(); + let request_api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + let conf = state.conf(); + + let admin_api_key: &masking::Secret<String> = &conf.secrets.get_inner().admin_api_key; + + if request_api_key == admin_api_key.peek() { + let (key_store, merchant) = + Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?; + let auth = AuthenticationData { + merchant_account: merchant, + platform_merchant_account: None, + key_store, + profile_id: None, + }; + return Ok(( + auth, + AuthenticationType::AdminApiAuthWithMerchantId { + merchant_id: merchant_id_from_route.clone(), + }, + )); + } + let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else { + return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( + "Api Key Authentication Failure: fallback merchant set not configured", + ); + }; + + let api_key = api_keys::PlaintextApiKey::from(request_api_key); + let hash_key = conf.api_keys.get_inner().get_hash_key()?; + let hashed_api_key = api_key.keyed_hash(hash_key.peek()); + + let stored_api_key = state + .store() + .find_api_key_by_hash_optional(hashed_api_key.into()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve API key")? + .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) + .attach_printable("Merchant not authenticated")?; + + if stored_api_key + .expires_at + .map(|expires_at| expires_at < date_time::now()) + .unwrap_or(false) + { + return Err(report!(errors::ApiErrorResponse::Unauthorized)) + .attach_printable("API key has expired"); + } + + if fallback_merchant_ids + .merchant_ids + .contains(&stored_api_key.merchant_id) + { + let (_, api_key_merchant) = + Self::fetch_merchant_key_store_and_account(&stored_api_key.merchant_id, state) + .await?; + let (route_key_store, route_merchant) = + Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?; + if api_key_merchant.get_org_id() == route_merchant.get_org_id() { + let auth = AuthenticationData { + merchant_account: route_merchant, + platform_merchant_account: None, + key_store: route_key_store, + profile_id: None, + }; + return Ok(( + auth.clone(), + AuthenticationType::MerchantId { + merchant_id: auth.merchant_account.get_id().clone(), + }, + )); + } + } + + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Authentication Failure")) + } +} + /// A helper struct to extract headers from the request pub(crate) struct HeaderMapStruct<'a> { headers: &'a HeaderMap,
2025-04-08T08:09:47Z
## 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 --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7744](https://github.com/juspay/hyperswitch/pull/7744) ### 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.113.0
2fdeb8580baffbf3fa3e5b49325a36ee02e4b176
2fdeb8580baffbf3fa3e5b49325a36ee02e4b176
juspay/hyperswitch
juspay__hyperswitch-7748
Bug: Add checks around Cypress mandates payments Just verifying the payment method status isn't enough. We also need to verify the existence of connector mandate id. this can be done by updating the `mitusingpmid` command.
2025-04-07T17:27:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds a check to verify if the `payment_status` is not any of `succeeded`, `partially_captured` or `requires_capture` and if so, then the `connector_mandate_id` should be `null`. ### 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). --> Verifying PM status isn't enough. We also need to check the existence of connector mandate id. Closes #7748 ## 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)? --> CI should pass. Also: CIT confirm, we should get `connector_mandate_id` <img width="510" alt="image" src="https://github.com/user-attachments/assets/41f74780-5b6e-404f-a9ec-2cf7619d9adf" /> MIT confirm, in NTID flow, `connector_mandate_id` will be `null` <img width="509" alt="image" src="https://github.com/user-attachments/assets/82c21ce9-261e-4457-9efc-c3e68398e555" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `npm run format` - [x] I addressed lints thrown by `npm run lint -- --fix` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
5730ddfc8893017f40a5f5a8c1b7f099cc0d22a9
5730ddfc8893017f40a5f5a8c1b7f099cc0d22a9
juspay/hyperswitch
juspay__hyperswitch-7745
Bug: Create authentications to fallback to ApiKeyAuth if AdminApiAuth fails Create two new authentication mechanisms that enhance the existing `AdminApiAuth` and `AdminApiAuthWithMerchantIdFromRoute` by allowing fallback to regular API key-based authentication when the admin key check fails. This will be used by Merchant Account and API Key routes.
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index c59b8471344..7cd4ce2d4bd 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -480,6 +480,7 @@ pub(crate) async fn fetch_raw_secrets( #[cfg(feature = "olap")] replica_database, secrets, + fallback_merchant_ids_api_key_auth: conf.fallback_merchant_ids_api_key_auth, locker: conf.locker, connectors: conf.connectors, forex_api, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index a4c454ec196..83591b15e36 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -66,6 +66,7 @@ pub struct Settings<S: SecretState> { pub redis: RedisSettings, pub log: Log, pub secrets: SecretStateContainer<Secrets, S>, + pub fallback_merchant_ids_api_key_auth: Option<FallbackMerchantIds>, pub locker: Locker, pub key_manager: SecretStateContainer<KeyManagerConfig, S>, pub connectors: Connectors, @@ -676,6 +677,13 @@ pub struct Secrets { pub master_enc_key: Secret<String>, } +#[derive(Debug, Default, Deserialize, Clone)] +#[serde(default)] +pub struct FallbackMerchantIds { + #[serde(deserialize_with = "deserialize_merchant_ids")] + pub merchant_ids: HashSet<id_type::MerchantId>, +} + #[derive(Debug, Clone, Default, Deserialize)] pub struct UserSettings { pub password_validity_in_days: u16, @@ -1271,6 +1279,53 @@ where })? } +fn deserialize_merchant_ids_inner( + value: impl AsRef<str>, +) -> Result<HashSet<id_type::MerchantId>, String> { + let (values, errors) = value + .as_ref() + .trim() + .split(',') + .map(|s| { + let trimmed = s.trim(); + id_type::MerchantId::wrap(trimmed.to_owned()).map_err(|error| { + format!( + "Unable to deserialize `{}` as `MerchantId`: {error}", + trimmed + ) + }) + }) + .fold( + (HashSet::new(), Vec::new()), + |(mut values, mut errors), result| match result { + Ok(t) => { + values.insert(t); + (values, errors) + } + Err(error) => { + errors.push(error); + (values, errors) + } + }, + ); + + if !errors.is_empty() { + Err(format!("Some errors occurred:\n{}", errors.join("\n"))) + } else { + Ok(values) + } +} + +fn deserialize_merchant_ids<'de, D>( + deserializer: D, +) -> Result<HashSet<id_type::MerchantId>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let s = String::deserialize(deserializer)?; + deserialize_merchant_ids_inner(s).map_err(serde::de::Error::custom) +} + impl<'de> Deserialize<'de> for TenantConfig { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 1c494542228..2be9058e906 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -186,7 +186,7 @@ pub async fn merchant_account_create( &req, json_payload.into_inner(), |state, _, req, _| create_merchant_account(state, req), - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallback, api_locking::LockAction::NotApplicable, )) .await @@ -249,7 +249,7 @@ pub async fn retrieve_merchant_account( payload, |state, _, req, _| get_merchant_account(state, req, None), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be MerchantAccountRead, but since FE is calling this API for @@ -350,7 +350,7 @@ pub async fn merchant_account_list( query_params.into_inner(), |state, _, request, _| list_merchant_account(state, request), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallback, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountRead, }, @@ -409,7 +409,7 @@ pub async fn update_merchant_account( json_payload.into_inner(), |state, _, req, _| merchant_account_update(state, &merchant_id, None, req), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantAccountWrite, diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 911617753d4..087e295dc8e 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -29,7 +29,7 @@ pub async fn api_key_create( api_keys::create_api_key(state, payload, auth_data.key_store).await }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyWrite, @@ -130,7 +130,7 @@ pub async fn api_key_retrieve( (merchant_id.clone(), key_id.clone()), |state, _, (merchant_id, key_id), _| api_keys::retrieve_api_key(state, merchant_id, key_id), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantApiKeyRead, @@ -166,7 +166,7 @@ pub async fn api_key_update( payload, |state, _, payload, _| api_keys::update_api_key(state, payload), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantApiKeyWrite, @@ -303,7 +303,7 @@ pub async fn api_key_list( api_keys::list_api_keys(state, merchant_id, limit, offset).await }, auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantApiKeyRead, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 7e3d6802b88..3b9fcfc0d8e 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -654,113 +654,20 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { - let merchant_id_from_route = self.0.clone(); - let api_key = get_api_key(request_headers) - .change_context(errors::ApiErrorResponse::Unauthorized)? - .trim(); - if api_key.is_empty() { - return Err(errors::ApiErrorResponse::Unauthorized) - .attach_printable("API key is empty"); - } - - let api_key = api_keys::PlaintextApiKey::from(api_key); - let hash_key = { - let config = state.conf(); - config.api_keys.get_inner().get_hash_key()? - }; - let hashed_api_key = api_key.keyed_hash(hash_key.peek()); - - let stored_api_key = state - .store() - .find_api_key_by_hash_optional(hashed_api_key.into()) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed - .attach_printable("Failed to retrieve API key")? - .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` - .attach_printable("Merchant not authenticated")?; - - if stored_api_key - .expires_at - .map(|expires_at| expires_at < date_time::now()) - .unwrap_or(false) - { - return Err(report!(errors::ApiErrorResponse::Unauthorized)) - .attach_printable("API key has expired"); - } - - let key_manager_state = &(&state.session_state()).into(); - - let key_store = state - .store() - .get_merchant_key_store_by_merchant_id( - key_manager_state, - &stored_api_key.merchant_id, - &state.store().get_master_key().to_vec().into(), - ) - .await - .change_context(errors::ApiErrorResponse::Unauthorized) - .attach_printable("Failed to fetch merchant key store for the merchant id")?; + let (auth_data, auth_type) = ApiKeyAuth + .authenticate_and_fetch(request_headers, state) + .await?; - let profile_id = - get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)? - .map(id_type::ProfileId::from_str) - .transpose() - .change_context(errors::ValidationError::IncorrectValueProvided { - field_name: "X-Profile-Id", - }) - .change_context(errors::ApiErrorResponse::Unauthorized)?; + let merchant_id_from_route = self.0.clone(); + let merchant_id_from_api_key = auth_data.merchant_account.get_id(); - if merchant_id_from_route != stored_api_key.merchant_id { + if merchant_id_from_route != *merchant_id_from_api_key { return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( "Merchant ID from route and Merchant ID from api-key in header do not match", ); } - let merchant = state - .store() - .find_merchant_account_by_merchant_id( - key_manager_state, - &stored_api_key.merchant_id, - &key_store, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; - - // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account - let (merchant, platform_merchant_account) = if state.conf().platform.enabled { - get_platform_merchant_account(state, request_headers, merchant).await? - } else { - (merchant, None) - }; - - let key_store = if platform_merchant_account.is_some() { - state - .store() - .get_merchant_key_store_by_merchant_id( - key_manager_state, - merchant.get_id(), - &state.store().get_master_key().to_vec().into(), - ) - .await - .change_context(errors::ApiErrorResponse::Unauthorized) - .attach_printable("Failed to fetch merchant key store for the merchant id")? - } else { - key_store - }; - - let auth = AuthenticationData { - merchant_account: merchant, - platform_merchant_account, - key_store, - profile_id, - }; - Ok(( - auth.clone(), - AuthenticationType::ApiKey { - merchant_id: auth.merchant_account.get_id().clone(), - key_id: stored_api_key.key_id, - }, - )) + Ok((auth_data, auth_type)) } } @@ -1398,6 +1305,198 @@ where } } +#[derive(Debug, Default)] +pub struct AdminApiAuthWithApiKeyFallback; + +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<(), A> for AdminApiAuthWithApiKeyFallback +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<((), AuthenticationType)> { + let request_api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + + let conf = state.conf(); + + let admin_api_key = &conf.secrets.get_inner().admin_api_key; + + if request_api_key == admin_api_key.peek() { + return Ok(((), AuthenticationType::AdminApiKey)); + } + let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else { + return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( + "Api Key Authentication Failure: fallback merchant set not configured", + ); + }; + + let api_key = api_keys::PlaintextApiKey::from(request_api_key); + let hash_key = conf.api_keys.get_inner().get_hash_key()?; + let hashed_api_key = api_key.keyed_hash(hash_key.peek()); + + let stored_api_key = state + .store() + .find_api_key_by_hash_optional(hashed_api_key.into()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve API key")? + .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) + .attach_printable("Merchant not authenticated")?; + + if stored_api_key + .expires_at + .map(|expires_at| expires_at < date_time::now()) + .unwrap_or(false) + { + return Err(report!(errors::ApiErrorResponse::Unauthorized)) + .attach_printable("API key has expired"); + } + + if fallback_merchant_ids + .merchant_ids + .contains(&stored_api_key.merchant_id) + { + return Ok(( + (), + AuthenticationType::ApiKey { + merchant_id: stored_api_key.merchant_id, + key_id: stored_api_key.key_id, + }, + )); + } + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Authentication Failure")) + } +} + +#[derive(Debug, Default)] +pub struct AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(pub id_type::MerchantId); + +#[cfg(feature = "v1")] +impl AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute { + async fn fetch_merchant_key_store_and_account<A: SessionStateInfo + Sync>( + merchant_id: &id_type::MerchantId, + state: &A, + ) -> RouterResult<(domain::MerchantKeyStore, domain::MerchantAccount)> { + let key_manager_state = &(&state.session_state()).into(); + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + let merchant = state + .store() + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + Ok((key_store, merchant)) + } +} + +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> + for AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let merchant_id_from_route: id_type::MerchantId = self.0.clone(); + let request_api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + let conf = state.conf(); + + let admin_api_key: &masking::Secret<String> = &conf.secrets.get_inner().admin_api_key; + + if request_api_key == admin_api_key.peek() { + let (key_store, merchant) = + Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?; + let auth = AuthenticationData { + merchant_account: merchant, + platform_merchant_account: None, + key_store, + profile_id: None, + }; + return Ok(( + auth, + AuthenticationType::AdminApiAuthWithMerchantId { + merchant_id: merchant_id_from_route.clone(), + }, + )); + } + let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else { + return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( + "Api Key Authentication Failure: fallback merchant set not configured", + ); + }; + + let api_key = api_keys::PlaintextApiKey::from(request_api_key); + let hash_key = conf.api_keys.get_inner().get_hash_key()?; + let hashed_api_key = api_key.keyed_hash(hash_key.peek()); + + let stored_api_key = state + .store() + .find_api_key_by_hash_optional(hashed_api_key.into()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve API key")? + .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) + .attach_printable("Merchant not authenticated")?; + + if stored_api_key + .expires_at + .map(|expires_at| expires_at < date_time::now()) + .unwrap_or(false) + { + return Err(report!(errors::ApiErrorResponse::Unauthorized)) + .attach_printable("API key has expired"); + } + + if fallback_merchant_ids + .merchant_ids + .contains(&stored_api_key.merchant_id) + { + let (_, api_key_merchant) = + Self::fetch_merchant_key_store_and_account(&stored_api_key.merchant_id, state) + .await?; + let (route_key_store, route_merchant) = + Self::fetch_merchant_key_store_and_account(&merchant_id_from_route, state).await?; + if api_key_merchant.get_org_id() == route_merchant.get_org_id() { + let auth = AuthenticationData { + merchant_account: route_merchant, + platform_merchant_account: None, + key_store: route_key_store, + profile_id: None, + }; + return Ok(( + auth.clone(), + AuthenticationType::MerchantId { + merchant_id: auth.merchant_account.get_id().clone(), + }, + )); + } + } + + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Admin Authentication Failure")) + } +} + /// A helper struct to extract headers from the request pub(crate) struct HeaderMapStruct<'a> { headers: &'a HeaderMap,
2025-04-07T13:20:20Z
## 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 authentication mechanisms that enhance the existing `AdminApiAuth` and `AdminApiAuthWithMerchantIdFromRoute` by allowing fallback to regular API key-based authentication when the admin key check fails. ### 1. `AdminApiAuthWithApiKeyFallback` - Used in routes where **no merchant context** is required. - Authenticates using: 1. `admin_api_key` 2. If that fails, falls back to: - Validating the provided `api-key` - Ensuring its associated `merchant_id` matches the configured `fallback_merchant_id` from the merchant_ids set. ### 2. `AdminApiAuthWithApiKeyFallbackWithMerchant` - Used in routes that require **full merchant context** (`AuthenticationData`) - Authenticates using: 1. `admin_api_key` — on success, loads `AuthenticationData` 2. If that fails: - Validates the provided `api-key` - Ensures: - The `merchant_id` from `api-key` also matches the configured `fallback_merchant_id` from the merchant_ids set. - If all conditions pass, loads and returns `AuthenticationData` ### 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). --> Some internal routes currently rely on `AdminApiAuth` using a shared `admin_api_key`. However, there are scenarios where we want to allow scoped access using an `api-key` associated with a specific merchant — **only if it matches a configured fallback merchant** from the merchant_ids set. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> The following APIs need to be validated with - AdminAPIKey - the API Key associated with the configured merchant_id in the ENVs. Tested by setting the ENV through ```bash ROUTER__FALLBACK_MERCHANT_IDS_API_KEY_AUTH__MERCHANT_IDS="merchant_1744036688, merchant_1744037289" cargo run ``` And also tested by specifying the values in the TOML file. #### Merchant Account - Create ```bash curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_PY3zf8m1f0HjtqxO7QS36ZRSGMP5u9IWsmDki4fwq5iY0W8e6RoF4WMwCLvlojJM' \ --data-raw '{ "merchant_id": "merchant_1744040286", "locker_id": "m0010", "merchant_name": "Nike", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "[email protected]", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "[email protected]", "secondary_phone": "cillum do dolor id", "website": "https://www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name":"john", "last_name":"Doe" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url":"https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "parent_merchant_id":"merchant_123", "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ], "organization_id": "org_aDQVlxlUjkkgfFO9rlwr" }' ``` #### Merchant Account - Retrieve ```bash curl --location 'http://localhost:8080/accounts/merchant_1744037289' \ --header 'Accept: application/json' \ --header 'api-key: dev_PY3zf8m1f0HjtqxO7QS36ZRSGMP5u9IWsmDki4fwq5iY0W8e6RoF4WMwCLvlojJM' ``` #### Merchant Account - Update ```bash curl --location 'http://localhost:8080/accounts/merchant_1744037289' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_PY3zf8m1f0HjtqxO7QS36ZRSGMP5u9IWsmDki4fwq5iY0W8e6RoF4WMwCLvlojJM' \ --data-raw '{ "merchant_id": "merchant_1744037289", "locker_id": "m0010", "merchant_name": "Nike New", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "[email protected]", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "[email protected]", "secondary_phone": "cillum do dolor id", "website": "https://www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name":"john", "last_name":"Doe" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url":"https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "parent_merchant_id":"merchant_123", "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` #### API Key - Create ```bash curl --location 'http://localhost:8080/api_keys/merchant_1744037289' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "API Key 1", "description": null, "expiration": "2038-01-19T03:14:08.000Z" }' ``` #### API Key - Retrieve ```bash curl --location 'http://localhost:8080/api_keys/merchant_1744037289/dev_Uyyi5bbsKgcsvwgtC4EJ' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` #### API Key - Update ```bash curl --location 'http://localhost:8080/api_keys/merchant_1744037289/dev_Uyyi5bbsKgcsvwgtC4EJ' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "Test API Key", "description": "My very awesome API key", "expiration": null }' ``` #### API Key - List ```bash curl --location 'http://localhost:8080/api_keys/merchant_1744036688/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` #### Merchant Account - List ## 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.113.0
c245ece19fb1b3988c61e12c0faa37c527cabd71
c245ece19fb1b3988c61e12c0faa37c527cabd71
juspay/hyperswitch
juspay__hyperswitch-7737
Bug: [ENHANCEMENT] expose configurations from payment links SDK has below functionalities which needs to be exposed as payment link configs 1. `labels`, possible values - floating, above, never 2. `paymentMethodsHeaderText` - for an optional text to be displayed above the payment form 3. `terms.cards`, possible values - auto, always, never
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 61cf7b26ac3..12e5308cbd4 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -14798,6 +14798,27 @@ "enable_button_only_on_form_ready": { "type": "boolean", "description": "Flag to enable the button only when the payment form is ready for submission" + }, + "payment_form_header_text": { + "type": "string", + "description": "Optional header for the SDK's payment form", + "nullable": true + }, + "payment_form_label_type": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkSdkLabelType" + } + ], + "nullable": true + }, + "show_card_terms": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkShowSdkTerms" + } + ], + "nullable": true } } }, @@ -14940,6 +14961,27 @@ "type": "boolean", "description": "Flag to enable the button only when the payment form is ready for submission", "nullable": true + }, + "payment_form_header_text": { + "type": "string", + "description": "Optional header for the SDK's payment form", + "nullable": true + }, + "payment_form_label_type": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkSdkLabelType" + } + ], + "nullable": true + }, + "show_card_terms": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkShowSdkTerms" + } + ], + "nullable": true } } }, @@ -14987,6 +15029,22 @@ } } }, + "PaymentLinkSdkLabelType": { + "type": "string", + "enum": [ + "above", + "floating", + "never" + ] + }, + "PaymentLinkShowSdkTerms": { + "type": "string", + "enum": [ + "always", + "auto", + "never" + ] + }, "PaymentLinkStatus": { "type": "string", "description": "Status Of the Payment Link", diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 0389ef35c56..6e9d3b12a7d 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -17229,6 +17229,27 @@ "enable_button_only_on_form_ready": { "type": "boolean", "description": "Flag to enable the button only when the payment form is ready for submission" + }, + "payment_form_header_text": { + "type": "string", + "description": "Optional header for the SDK's payment form", + "nullable": true + }, + "payment_form_label_type": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkSdkLabelType" + } + ], + "nullable": true + }, + "show_card_terms": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkShowSdkTerms" + } + ], + "nullable": true } } }, @@ -17371,6 +17392,27 @@ "type": "boolean", "description": "Flag to enable the button only when the payment form is ready for submission", "nullable": true + }, + "payment_form_header_text": { + "type": "string", + "description": "Optional header for the SDK's payment form", + "nullable": true + }, + "payment_form_label_type": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkSdkLabelType" + } + ], + "nullable": true + }, + "show_card_terms": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkShowSdkTerms" + } + ], + "nullable": true } } }, @@ -17418,6 +17460,22 @@ } } }, + "PaymentLinkSdkLabelType": { + "type": "string", + "enum": [ + "above", + "floating", + "never" + ] + }, + "PaymentLinkShowSdkTerms": { + "type": "string", + "enum": [ + "always", + "auto", + "never" + ] + }, "PaymentLinkStatus": { "type": "string", "description": "Status Of the Payment Link", diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 5d3f7c5dc8f..a9a8525f65b 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2892,6 +2892,14 @@ pub struct PaymentLinkConfigRequest { pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: Option<bool>, + /// Optional header for the SDK's payment form + pub payment_form_header_text: Option<String>, + /// Label type in the SDK's payment form + #[schema(value_type = Option<PaymentLinkSdkLabelType>, example = "floating")] + pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, + /// Boolean for controlling whether or not to show the explicit consent for storing cards + #[schema(value_type = Option<PaymentLinkShowSdkTerms>, example = "always")] + pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] @@ -2979,6 +2987,14 @@ pub struct PaymentLinkConfig { pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: bool, + /// Optional header for the SDK's payment form + pub payment_form_header_text: Option<String>, + /// Label type in the SDK's payment form + #[schema(value_type = Option<PaymentLinkSdkLabelType>, example = "floating")] + pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, + /// Boolean for controlling whether or not to show the explicit consent for storing cards + #[schema(value_type = Option<PaymentLinkShowSdkTerms>, example = "always")] + pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 859dba9b59a..61efe59c66b 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -8023,6 +8023,9 @@ pub struct PaymentLinkDetails { pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, + pub payment_form_header_text: Option<String>, + pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, + pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, } #[derive(Debug, serde::Serialize, Clone)] @@ -8041,6 +8044,9 @@ pub struct SecurePaymentLinkDetails { pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, + pub payment_form_header_text: Option<String>, + pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, + pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, } #[derive(Debug, serde::Serialize)] diff --git a/crates/common_enums/src/enums/ui.rs b/crates/common_enums/src/enums/ui.rs index aec6c7ed64a..eaa63e89e39 100644 --- a/crates/common_enums/src/enums/ui.rs +++ b/crates/common_enums/src/enums/ui.rs @@ -90,6 +90,54 @@ pub enum PaymentLinkDetailsLayout { Layout2, } +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + Hash, + PartialEq, + Serialize, + Deserialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "lowercase")] +#[strum(serialize_all = "lowercase")] +pub enum PaymentLinkSdkLabelType { + #[default] + Above, + Floating, + Never, +} + +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + Hash, + PartialEq, + Serialize, + Deserialize, + strum::Display, + strum::EnumString, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "lowercase")] +#[strum(serialize_all = "lowercase")] +pub enum PaymentLinkShowSdkTerms { + Always, + #[default] + Auto, + Never, +} + impl<'de> Deserialize<'de> for ElementSize { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 94da0f0438b..07ca6cb46dc 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -681,6 +681,9 @@ pub struct PaymentLinkConfigRequest { pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: Option<bool>, + pub payment_form_header_text: Option<String>, + pub payment_form_label_type: Option<common_enums::PaymentLinkSdkLabelType>, + pub show_card_terms: Option<common_enums::PaymentLinkShowSdkTerms>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 445cc6eab3c..634626a4b1f 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -196,6 +196,12 @@ pub struct PaymentLinkConfigRequestForPayments { Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: Option<bool>, + /// Optional header for the SDK's payment form + pub payment_form_header_text: Option<String>, + /// Label type in the SDK's payment form + pub payment_form_label_type: Option<common_enums::PaymentLinkSdkLabelType>, + /// Boolean for controlling whether or not to show the explicit consent for storing cards + pub show_card_terms: Option<common_enums::PaymentLinkShowSdkTerms>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments); diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index a488c5aaa53..73f42dbd153 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -422,6 +422,9 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, + payment_form_header_text: item.payment_form_header_text, + payment_form_label_type: item.payment_form_label_type, + show_card_terms: item.show_card_terms, } } fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest { @@ -446,6 +449,9 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, + payment_form_header_text, + payment_form_label_type, + show_card_terms, } = self; api_models::admin::PaymentLinkConfigRequest { theme, @@ -474,6 +480,9 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, + payment_form_header_text, + payment_form_label_type, + show_card_terms, } } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 47a5ad25f76..40cedb1e402 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -329,6 +329,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::FeatureStatus, api_models::enums::MerchantProductType, api_models::enums::CtpServiceProvider, + api_models::enums::PaymentLinkSdkLabelType, + api_models::enums::PaymentLinkShowSdkTerms, api_models::admin::MerchantConnectorCreate, api_models::admin::AdditionalMerchantData, api_models::admin::ConnectorWalletDetails, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index efc9dc9076b..ead503d1bb9 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -295,6 +295,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::UIWidgetFormLayout, api_models::enums::MerchantProductType, api_models::enums::CtpServiceProvider, + api_models::enums::PaymentLinkSdkLabelType, + api_models::enums::PaymentLinkShowSdkTerms, api_models::admin::MerchantConnectorCreate, api_models::admin::AdditionalMerchantData, api_models::admin::CardTestingGuardConfig, diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index 48004dd740b..c2945335b52 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -139,6 +139,9 @@ pub async fn form_payment_link_data( sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, + payment_form_header_text: None, + payment_form_label_type: None, + show_card_terms: None, } }; @@ -296,6 +299,9 @@ pub async fn form_payment_link_data( payment_link_ui_rules: payment_link_config.payment_link_ui_rules.clone(), status: payment_intent.status, enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready, + payment_form_header_text: payment_link_config.payment_form_header_text.clone(), + payment_form_label_type: payment_link_config.payment_form_label_type, + show_card_terms: payment_link_config.show_card_terms, }; Ok(( @@ -356,6 +362,9 @@ pub async fn initiate_secure_payment_link_flow( payment_link_ui_rules: payment_link_config.payment_link_ui_rules, enable_button_only_on_form_ready: payment_link_config .enable_button_only_on_form_ready, + payment_form_header_text: payment_link_config.payment_form_header_text, + payment_form_label_type: payment_link_config.payment_form_label_type, + show_card_terms: payment_link_config.show_card_terms, }; let js_script = format!( "window.__PAYMENT_DETAILS = {}", @@ -674,6 +683,9 @@ pub fn get_payment_link_config_based_on_priority( payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, + payment_form_header_text, + payment_form_label_type, + show_card_terms, ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, @@ -688,6 +700,9 @@ pub fn get_payment_link_config_based_on_priority( (payment_button_text_colour), (sdk_ui_rules), (payment_link_ui_rules), + (payment_form_header_text), + (payment_form_label_type), + (show_card_terms), ); let payment_link_config = @@ -716,6 +731,9 @@ pub fn get_payment_link_config_based_on_priority( sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, + payment_form_header_text, + payment_form_label_type, + show_card_terms, }; Ok((payment_link_config, domain_name)) @@ -827,6 +845,9 @@ pub async fn get_payment_link_status( sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, + payment_form_header_text: None, + payment_form_label_type: None, + show_card_terms: None, } }; diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js index f9b0fe892cf..effd27cc64a 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js @@ -12,6 +12,7 @@ function initializeSDK() { var paymentDetails = window.__PAYMENT_DETAILS; var clientSecret = paymentDetails.client_secret; var sdkUiRules = paymentDetails.sdk_ui_rules; + var labelType = paymentDetails.payment_form_label_type; var appearance = { variables: { colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)", @@ -25,9 +26,12 @@ function initializeSDK() { colorBackground: "rgb(255, 255, 255)", }, }; - if (sdkUiRules !== null && typeof sdkUiRules === "object" && Object.getPrototypeOf(sdkUiRules) === Object.prototype) { + if (isObject(sdkUiRules)) { appearance.rules = sdkUiRules; } + if (labelType !== null && typeof labelType === "string") { + appearance.labels = labelType; + } // @ts-ignore hyper = window.Hyper(pub_key, { isPreloadEnabled: false, @@ -70,11 +74,18 @@ function initializeSDK() { hideCardNicknameField: hideCardNicknameField, customMessageForCardTerms: paymentDetails.custom_message_for_card_terms, }; - // @ts-ignore + var showCardTerms = paymentDetails.show_card_terms; + if (showCardTerms !== null && typeof showCardTerms === "string") { + unifiedCheckoutOptions.terms = { + card: showCardTerms + }; + } + var paymentMethodsHeaderText = paymentDetails.payment_form_header_text; + if (paymentMethodsHeaderText !== null && typeof paymentMethodsHeaderText === "string") { + unifiedCheckoutOptions.paymentMethodsHeaderText = paymentMethodsHeaderText; + } unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions); - // @ts-ignore mountUnifiedCheckout("#unified-checkout"); - // @ts-ignore showSDK(paymentDetails.display_sdk_only, paymentDetails.enable_button_only_on_form_ready); let shimmer = document.getElementById("payment-details-shimmer"); diff --git a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js index 12ae76a2085..446428e6ff3 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js @@ -33,6 +33,7 @@ if (!isFramed) { var paymentDetails = window.__PAYMENT_DETAILS; var clientSecret = paymentDetails.client_secret; var sdkUiRules = paymentDetails.sdk_ui_rules; + var labelType = paymentDetails.payment_form_label_type; var appearance = { variables: { colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)", @@ -46,9 +47,12 @@ if (!isFramed) { colorBackground: "rgb(255, 255, 255)", }, }; - if (sdkUiRules !== null && typeof sdkUiRules === "object" && Object.getPrototypeOf(sdkUiRules) === Object.prototype) { + if (isObject(sdkUiRules)) { appearance.rules = sdkUiRules; } + if (labelType !== null && typeof labelType === "string") { + appearance.labels = labelType; + } // @ts-ignore hyper = window.Hyper(pub_key, { isPreloadEnabled: false, @@ -93,11 +97,19 @@ if (!isFramed) { showCardFormByDefault: paymentDetails.show_card_form_by_default, customMessageForCardTerms: paymentDetails.custom_message_for_card_terms, }; - // @ts-ignore + var showCardTerms = paymentDetails.show_card_terms; + if (showCardTerms !== null && typeof showCardTerms === "string") { + unifiedCheckoutOptions.terms = { + card: showCardTerms + }; + } + var paymentMethodsHeaderText = paymentDetails.payment_form_header_text; + if (paymentMethodsHeaderText !== null && typeof paymentMethodsHeaderText === "string") { + unifiedCheckoutOptions.paymentMethodsHeaderText = paymentMethodsHeaderText; + } + unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions); - // @ts-ignore mountUnifiedCheckout("#unified-checkout"); - // @ts-ignore showSDK(paymentDetails.display_sdk_only, paymentDetails.enable_button_only_on_form_ready); let shimmer = document.getElementById("payment-details-shimmer"); diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5b6b014aca4..d8014768719 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -4529,6 +4529,9 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> sdk_ui_rules: config.sdk_ui_rules, payment_link_ui_rules: config.payment_link_ui_rules, enable_button_only_on_form_ready: config.enable_button_only_on_form_ready, + payment_form_header_text: config.payment_form_header_text, + payment_form_label_type: config.payment_form_label_type, + show_card_terms: config.show_card_terms, } } } @@ -4600,6 +4603,9 @@ impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments> sdk_ui_rules: config.sdk_ui_rules, payment_link_ui_rules: config.payment_link_ui_rules, enable_button_only_on_form_ready: config.enable_button_only_on_form_ready, + payment_form_header_text: config.payment_form_header_text, + payment_form_label_type: config.payment_form_label_type, + show_card_terms: config.show_card_terms, } } } diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index c9ff466af00..b889c41e7bc 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -152,7 +152,7 @@ pub async fn customers_list( let flow = Flow::CustomersList; let payload = query.into_inner(); - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -174,7 +174,7 @@ pub async fn customers_list( req.headers(), ), api_locking::LockAction::NotApplicable, - ) + )) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 6d529b12809..04690465466 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -2188,6 +2188,9 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, + payment_form_header_text: item.payment_form_header_text, + payment_form_label_type: item.payment_form_label_type, + show_card_terms: item.show_card_terms, } } } @@ -2219,6 +2222,9 @@ impl ForeignFrom<diesel_models::business_profile::PaymentLinkConfigRequest> sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, + payment_form_header_text: item.payment_form_header_text, + payment_form_label_type: item.payment_form_label_type, + show_card_terms: item.show_card_terms, } } }
2025-04-07T11:51:22Z
## 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 exposes three configurations for payment links 1. `payment_form_header_text` - for rendering a header text for payment links 2. `payment_form_label_type` - for specifying the type of payment form labels (floating / above / never) 3. `show_card_terms` - for controlling visibility of the terms for cards (auto / always / never) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 4. `crates/router/src/configs` 5. `loadtest/config` --> ## Motivation and Context Helps in exposing UI functionalities through some configs for SDK. ## How did you test it? Tested locally <details> <summary>Create payment link with new configs</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ML2p8kRGcMvi4oQ3cPnIfz5R2rO31efjWKXzgMnbRCnj5pUpjiki8K2HONlmMAb4' \ --data-raw '{"authentication_type":"three_ds","customer_id":"cus_9SCrW9x19m2WbGYHprJS","profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","amount":100,"currency":"EUR","payment_link":true,"setup_future_usage":"off_session","capture_method":"automatic","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"NL","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"return_url":"https://example.com","payment_link_config":{"theme":"#2167AE","enable_button_only_on_form_ready":true,"display_sdk_only":true,"show_card_terms":"never","payment_form_label_type":"floating","payment_form_header_text":"Detalles de tu tarjeta","payment_link_ui_rules":{"#submit":{"height":"max-content","borderRadius":"50px","padding":"14px 20px","marginTop":"48px","fontSize":"20px"},"#submit.not-ready":{"backgroundColor":"#A6ADAF !important"},"#submit.processing":{"paddingLeft":"50px !important","paddingRight":"50px !important"}},"sdk_ui_rules":{".Input, .Input:focus, .Input--invalid, .Input--empty":{"border":"none","boxShadow":"none","borderRadius":"28px","paddingLeft":"22px !important","paddingBottom":"2px !important","backgroundColor":"rgb(231, 234, 235) !important","height":"56px","fontSize":"20px"},".Input, .Input:focus, .Input--empty":{"color":"#23366F"},".Input--invalid":{"border":"2px solid #CB4B40 !important"},".Label":{"marginLeft":"22px","color":"#2167AE","opacity":"1 !important","bottom":"5px"},".Label--invalid, .Input--invalid, .Error":{"color":"#CB4B40 !important","opacity":"1 !important"},".Label--floating":{"opacity":"1 !important"},".InputLogo--empty":{"color":"#979797"},".InputLogo":{"color":"#23366F"},".InputLogo--invalid":{"color":"#CB4B40"},".PaymentLabel":{"color":"#23366F !important","fontSize":"24px"}}}}' Response {"payment_id":"pay_McmUUZfc21SHM7Hpc9Sr","merchant_id":"merchant_1743758708","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_McmUUZfc21SHM7Hpc9Sr_secret_ohEWaukkfjWDkoB2U7pc","created":"2025-04-07T11:49:19.273Z","currency":"EUR","customer_id":"cus_9SCrW9x19m2WbGYHprJS","customer":{"id":"cus_9SCrW9x19m2WbGYHprJS","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"NL","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_9SCrW9x19m2WbGYHprJS","created_at":1744026559,"expires":1744030159,"secret":"epk_74f58545483841e7a27ef0bddca9b8b5"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1743758708/pay_McmUUZfc21SHM7Hpc9Sr?locale=en","secure_link":"http://localhost:8080/payment_link/s/merchant_1743758708/pay_McmUUZfc21SHM7Hpc9Sr?locale=en","payment_link_id":"plink_1VJHoVm7E71veuUAJhI8"},"profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-07T12:04:19.254Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-07T11:49:19.358Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} Verify below things 1. Label is floating when 2. Payment form has a header text 3. Card terms are missing for off_session payment type <img width="627" alt="Screenshot 2025-04-07 at 5 21 04 PM" src="https://github.com/user-attachments/assets/5e395ab6-44e7-44ab-9660-57603f79c4c2" /> </details> ## 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.113.0
68e22eefe81980666737e34336210dbea57ff40d
68e22eefe81980666737e34336210dbea57ff40d
juspay/hyperswitch
juspay__hyperswitch-7734
Bug: chore: address Rust 1.86.0 clippy lints Address the clippy lints occurring due to new rust version 1.86.0 See https://github.com/juspay/hyperswitch/issues/3391 for more information.
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 11c9b17fae6..c96fdd3ca57 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -125,7 +125,7 @@ impl<const PRECISION: u8> Percentage<PRECISION> { fn is_valid_precision_length(value: &str) -> bool { if value.contains('.') { // if string has '.' then take the decimal part and verify precision length - match value.split('.').last() { + match value.split('.').next_back() { Some(decimal_part) => { decimal_part.trim_end_matches('0').len() <= <u8 as Into<usize>>::into(PRECISION) } diff --git a/crates/common_utils/src/validation.rs b/crates/common_utils/src/validation.rs index 9403e6720a9..007674a0db1 100644 --- a/crates/common_utils/src/validation.rs +++ b/crates/common_utils/src/validation.rs @@ -26,6 +26,8 @@ pub fn validate_phone_number(phone_number: &str) -> Result<(), ValidationError> pub fn validate_email(email: &str) -> CustomResult<(), ValidationError> { #[deny(clippy::invalid_regex)] static EMAIL_REGEX: Lazy<Option<Regex>> = Lazy::new(|| { + #[allow(unknown_lints)] + #[allow(clippy::manual_ok_err)] match Regex::new( r"^(?i)[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$", ) { diff --git a/crates/euclid/src/backend/vir_interpreter.rs b/crates/euclid/src/backend/vir_interpreter.rs index 7fde8721be0..50420ecd1c4 100644 --- a/crates/euclid/src/backend/vir_interpreter.rs +++ b/crates/euclid/src/backend/vir_interpreter.rs @@ -40,13 +40,15 @@ where } fn eval_statement(stmt: &vir::ValuedIfStatement, ctx: &types::Context) -> bool { - Self::eval_condition(&stmt.condition, ctx) - .then(|| { + if Self::eval_condition(&stmt.condition, ctx) { + { stmt.nested.as_ref().map_or(true, |nested_stmts| { nested_stmts.iter().any(|s| Self::eval_statement(s, ctx)) }) - }) - .unwrap_or(false) + } + } else { + false + } } fn eval_rule(rule: &vir::ValuedRule<O>, ctx: &types::Context) -> bool { diff --git a/crates/hyperswitch_connectors/src/connectors/bluesnap.rs b/crates/hyperswitch_connectors/src/connectors/bluesnap.rs index b42e3b7f1fc..165fde6476b 100644 --- a/crates/hyperswitch_connectors/src/connectors/bluesnap.rs +++ b/crates/hyperswitch_connectors/src/connectors/bluesnap.rs @@ -747,7 +747,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .change_context(errors::ConnectorError::ResponseHandlingFailed)?; // If location headers are not present connector will return 4XX so this error will never be propagated let payment_fields_token = location .split('/') - .last() + .next_back() .ok_or(errors::ConnectorError::ResponseHandlingFailed)? .to_string(); diff --git a/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs index 7c49cfe93dc..b8ebe76e5d1 100644 --- a/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs @@ -308,7 +308,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues let apple_pay_payment_data = payment_method_data.get_applepay_decoded_payment_data()?; let apple_pay_payment_data: ApplePayEncodedPaymentData = apple_pay_payment_data - .expose()[..] + .expose() .as_bytes() .parse_struct("ApplePayEncodedPaymentData") .change_context(errors::ConnectorError::InvalidWalletToken { diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index 101a9b753ad..11e6de3ac6b 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -402,7 +402,7 @@ impl ChargebeeCustomer { .ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)? .to_string(); let mandate_id = parts - .last() + .next_back() .ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)? .to_string(); Ok(ChargebeeMandateDetails { diff --git a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs index 57caa65ba8c..57e207c9c78 100644 --- a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs @@ -1373,7 +1373,7 @@ pub fn construct_file_upload_request( .file_type .as_ref() .split('/') - .last() + .next_back() .unwrap_or_default() )) .mime_str(request.file_type.as_ref()) diff --git a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs index 086763635b6..59c76c64be5 100644 --- a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs @@ -78,8 +78,8 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) - | PaymentMethodData::MandatePayment {} - | PaymentMethodData::Reward {} + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::MobilePayment(_) diff --git a/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs b/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs index 31265162ca0..03e7d9bd298 100644 --- a/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs @@ -137,8 +137,8 @@ impl TryFrom<&ForteRouterData<&types::PaymentsAuthorizeRouterData>> for FortePay | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) - | PaymentMethodData::MandatePayment {} - | PaymentMethodData::Reward {} + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) diff --git a/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs index 400125e2cdc..ee658d8a0fa 100644 --- a/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs @@ -353,8 +353,8 @@ impl TryFrom<&NoonRouterData<&PaymentsAuthorizeRouterData>> for NoonPaymentsRequ | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) - | PaymentMethodData::MandatePayment {} - | PaymentMethodData::Reward {} + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) diff --git a/crates/hyperswitch_connectors/src/connectors/paypal.rs b/crates/hyperswitch_connectors/src/connectors/paypal.rs index 5d2d6db91fb..02d2b0e7aef 100644 --- a/crates/hyperswitch_connectors/src/connectors/paypal.rs +++ b/crates/hyperswitch_connectors/src/connectors/paypal.rs @@ -148,7 +148,7 @@ impl Paypal { if let Some(field) = error .field .as_ref() - .and_then(|field| field.split('/').last()) + .and_then(|field| field.split('/').next_back()) { reason.push_str(&format!(", field - {field}")); } diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs index 95f9979762a..b843b4d0c38 100644 --- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs @@ -331,8 +331,8 @@ impl TryFrom<&ConnectorAuthType> for SquareAuthType { | ConnectorAuthType::SignatureKey { .. } | ConnectorAuthType::MultiAuthKey { .. } | ConnectorAuthType::CurrencyAuthKey { .. } - | ConnectorAuthType::TemporaryAuth { .. } - | ConnectorAuthType::NoKey { .. } + | ConnectorAuthType::TemporaryAuth + | ConnectorAuthType::NoKey | ConnectorAuthType::CertificateAuth { .. } => { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } diff --git a/crates/hyperswitch_connectors/src/connectors/volt.rs b/crates/hyperswitch_connectors/src/connectors/volt.rs index 5bd6065d57f..a8c5a5298d6 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt.rs @@ -663,7 +663,7 @@ impl webhooks::IncomingWebhook for Volt { let user_agent = utils::get_header_key_value(webhook_headers::USER_AGENT, request.headers)?; let version = user_agent .split('/') - .last() + .next_back() .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?; Ok(format!( "{}|{}|{}", diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay.rs b/crates/hyperswitch_connectors/src/connectors/worldpay.rs index a42bffa3bc0..4628eaf116e 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay.rs @@ -1099,13 +1099,14 @@ impl IncomingWebhook for Worldpay { request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - let event_signature = get_header_key_value("Event-Signature", request.headers)?.split(','); + let mut event_signature = + get_header_key_value("Event-Signature", request.headers)?.split(','); let sign_header = event_signature - .last() + .next_back() .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; let signature = sign_header .split('/') - .last() + .next_back() .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; hex::decode(signature).change_context(errors::ConnectorError::WebhookResponseEncodingFailed) } diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs index ba3065c752b..d5ebe6d6957 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs @@ -282,7 +282,7 @@ impl VoucherData::PagoEfectivo => ZenPaymentChannels::PclBoacompraPagoefectivo, VoucherData::RedCompra => ZenPaymentChannels::PclBoacompraRedcompra, VoucherData::RedPagos => ZenPaymentChannels::PclBoacompraRedpagos, - VoucherData::Oxxo { .. } + VoucherData::Oxxo | VoucherData::Alfamart { .. } | VoucherData::Indomaret { .. } | VoucherData::SevenEleven { .. } diff --git a/crates/router/src/connector/netcetera/netcetera_types.rs b/crates/router/src/connector/netcetera/netcetera_types.rs index 4869c228b41..b79eab200e5 100644 --- a/crates/router/src/connector/netcetera/netcetera_types.rs +++ b/crates/router/src/connector/netcetera/netcetera_types.rs @@ -1113,8 +1113,8 @@ pub struct MerchantRiskIndicator { /// New field introduced: /// - transChar -> Indicates to the ACS specific transactions identified by the Merchant. /// - Size: Variable, 1-2 elements. JSON Data Type: Array of String. Accepted values: - /// - 01 -> Cryptocurrency transaction - /// - 02 -> NFT transaction + /// - 01 -> Cryptocurrency transaction + /// - 02 -> NFT transaction trans_char: Option<String>, } @@ -1558,19 +1558,19 @@ pub struct Sdk { /// Creates a JSON object of the following data as the JWS payload to be signed: /// /// - SDK Reference Number -> Identifies the vendor and version of the 3DS SDK that is utilised for a specific - /// transaction. The value is assigned by EMVCo when the Letter of Approval of the - /// specific 3DS SDK is issued. The field is limited to 32 characters. + /// transaction. The value is assigned by EMVCo when the Letter of Approval of the + /// specific 3DS SDK is issued. The field is limited to 32 characters. /// - SDK Signature Timestamp -> Date and time indicating when the 3DS SDK generated the Split-SDK Server Signed - /// Content converted into UTC. The value is limited to 14 characters. Accepted - /// format: YYYYMMDDHHMMSS. + /// Content converted into UTC. The value is limited to 14 characters. Accepted + /// format: YYYYMMDDHHMMSS. /// - SDK Transaction ID -> Universally unique transaction identifier assigned by the 3DS SDK to identify a - /// single transaction. The field is limited to 36 characters and it shall be in a - /// canonical format as defined in IETF RFC 4122. This may utilize any of the specified - /// versions as long as the output meets specific requirements. + /// single transaction. The field is limited to 36 characters and it shall be in a + /// canonical format as defined in IETF RFC 4122. This may utilize any of the specified + /// versions as long as the output meets specific requirements. /// - Split-SDK Server ID -> DS assigned Split-SDK Server identifier. Each DS can provide a unique ID to each - /// Split-SDK Server on an individual basis. The field is limited to 32 characters. - /// Any individual DS may impose specific formatting and character requirements on the - /// contents of this field. + /// Split-SDK Server on an individual basis. The field is limited to 32 characters. + /// Any individual DS may impose specific formatting and character requirements on the + /// contents of this field. /// /// Generates a digital signature of the full JSON object according to JWS (RFC 7515) using JWS Compact /// Serialization. The parameter values for this version of the specification and to be included in the JWS @@ -1705,7 +1705,7 @@ pub struct SplitSdkType { /// Limited Split-SDK Indicator: If the Split-SDK client has limited capabilities /// - Length: 1 character /// - Value accepted: - /// • Y = Limited + /// • Y = Limited /// - Only present if value = Y limited_ind: Option<String>, } diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/router/src/connector/netcetera/transformers.rs index 1751c70fe97..8e3fb560ceb 100644 --- a/crates/router/src/connector/netcetera/transformers.rs +++ b/crates/router/src/connector/netcetera/transformers.rs @@ -700,9 +700,9 @@ pub struct ResultsResponseData { /// - `U`: Authentication / Account verification could not be performed; technical or other problem. /// - `C`: A challenge is required to complete the authentication. /// - `R`: Authentication / Account verification Rejected. Issuer is rejecting authentication/verification - /// and request that authorization not be attempted. + /// and request that authorization not be attempted. /// - `A`: Attempts processing performed; Not authenticated / verified, but a proof of attempt - /// authentication / verification is provided. + /// authentication / verification is provided. /// - `D`: A challenge is required to complete the authentication. Decoupled Authentication confirmed. /// - `I`: Informational Only; 3DS Requestor challenge preference acknowledged. pub trans_status: Option<common_enums::TransactionStatus>, diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index 093e0a72d10..ee299403b69 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -178,7 +178,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> | errors::ConnectorError::RequestTimeoutReceived | errors::ConnectorError::CurrencyNotSupported { .. } | errors::ConnectorError::InvalidConnectorConfig { .. } - | errors::ConnectorError::AmountConversionFailed { .. } + | errors::ConnectorError::AmountConversionFailed | errors::ConnectorError::GenericError { .. } => { err.change_context(errors::ApiErrorResponse::RefundFailed { data: None }) } @@ -369,7 +369,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> | errors::ConnectorError::RequestTimeoutReceived | errors::ConnectorError::CurrencyNotSupported { .. } | errors::ConnectorError::ProcessingStepFailed(None) - | errors::ConnectorError::AmountConversionFailed { .. } + | errors::ConnectorError::AmountConversionFailed | errors::ConnectorError::GenericError { .. } => { logger::error!(%error,"Setup Mandate flow failed"); errors::ApiErrorResponse::PaymentAuthorizationFailed { data: None } diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs index a0f651b93c3..e8b1e83b250 100644 --- a/crates/router/src/events/audit_events.rs +++ b/crates/router/src/events/audit_events.rs @@ -78,9 +78,9 @@ impl Event for AuditEvent { AuditEventType::RefundFail => "refund_fail", AuditEventType::PaymentCancelled { .. } => "payment_cancelled", AuditEventType::PaymentUpdate { .. } => "payment_update", - AuditEventType::PaymentApprove { .. } => "payment_approve", - AuditEventType::PaymentCreate { .. } => "payment_create", - AuditEventType::PaymentStatus { .. } => "payment_status", + AuditEventType::PaymentApprove => "payment_approve", + AuditEventType::PaymentCreate => "payment_create", + AuditEventType::PaymentStatus => "payment_status", AuditEventType::PaymentCompleteAuthorize => "payment_complete_authorize", AuditEventType::PaymentReject { .. } => "payment_rejected", }; diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index 84caf9ad765..d06f4a604c9 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -68,7 +68,7 @@ impl CashtocodeTest { router_return_url: Some(String::from("https://google.com")), webhook_url: None, complete_authorize_url: None, - customer_id: if let Ok(id) = cust_id { Some(id) } else { None }, + customer_id: cust_id.ok(), surcharge_details: None, request_incremental_authorization: false, metadata: None,
2025-04-07T08:57:34Z
## Type of Change - [ ] 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.86.0 https://rust-lang.github.io/rust-clippy/master/index.html ### Additional Changes - [ ] 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)? --> CI checks should pass as this PR addresses clippy lints. 1. ran `rustc --version` ![image](https://github.com/user-attachments/assets/b154032b-dff4-4582-b525-9b97ce83ce55) 3. ran `just clippy` with new rust version (1.86.0) <img width="1004" alt="Screenshot 2025-04-07 at 5 46 05 PM" src="https://github.com/user-attachments/assets/5951c74e-8f3d-44e2-8172-e376c01c2e9d" /> 4. ran `just clippy_v2` with new rust version (1.86.0) <img width="1019" alt="Screenshot 2025-04-07 at 5 46 38 PM" src="https://github.com/user-attachments/assets/ecdf5c2a-dc31-45b4-be01-cedc041cf59d" /> ## 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.113.0
0a5d2495435ff737dd952c97e5dcd0fc52839258
0a5d2495435ff737dd952c97e5dcd0fc52839258
juspay/hyperswitch
juspay__hyperswitch-7728
Bug: [DOCS] Intelligent router open api ### Feature Description Open API spec for intelligent router ### Possible Implementation Open API spec for intelligent router ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference/hyperswitch_intelligent_router_open_api_spec.yml b/api-reference/hyperswitch_intelligent_router_open_api_spec.yml new file mode 100644 index 00000000000..34eec90726e --- /dev/null +++ b/api-reference/hyperswitch_intelligent_router_open_api_spec.yml @@ -0,0 +1,653 @@ +openapi: 3.0.0 +info: + title: Dynamic routing - OpenAPI 3.0 + description: This the the open API 3.0 specification for the dynamic routing. + version: 1.0.0 +paths: + /success_rate.SuccessRateCalculator/FetchSuccessRate: + post: + summary: Fetch success rate for an entity + operationId: fetchSuccessRate + description: Calculates success rate for an entity based on provided parameters and labels + tags: + - Success Rate + parameters: + - name: x-tenant-id + in: header + required: true + schema: + type: string + example: public + - name: x-profile-id + in: header + required: true + schema: + type: string + example: pro_WX0giXQnzk2wQJjkKVBX + - name: x-api-key + in: header + required: true + schema: + type: string + example: dev_VLzQTxkPq3ALj2mlfiHL4mMtXca4uplOIOLaKEzmWAmNBXZjwsuv5bCLjnf0QYHm + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CalSuccessRateRequest" + example: + id: "merchant1" + params: "card" + labels: ["stripe", "adyen"] + responses: + "200": + description: Success rate calculated successfully + content: + application/json: + schema: + $ref: "#/components/schemas/CalSuccessRateResponse" + "400": + description: Invalid request parameters + "500": + description: Internal server error + + /success_rate.SuccessRateCalculator/UpdateSuccessRateWindow: + post: + summary: Update success rate window + operationId: updateSuccessRateWindow + description: Updates the success rate calculation window with new data points + tags: + - Success Rate + parameters: + - name: x-tenant-id + in: header + required: true + schema: + type: string + example: public + - name: x-profile-id + in: header + required: true + schema: + type: string + example: pro_WX0giXQnzk2wQJjkKVBX + - name: x-api-key + in: header + required: true + schema: + type: string + example: dev_VLzQTxkPq3ALj2mlfiHL4mMtXca4uplOIOLaKEzmWAmNBXZjwsuv5bCLjnf0QYHm + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateSuccessRateWindowRequest" + responses: + "200": + description: Window updated successfully + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateSuccessRateWindowResponse" + "400": + description: Invalid request parameters + "500": + description: Internal server error + + /success_rate.SuccessRateCalculator/InvalidateWindows: + post: + summary: Invalidate windows + operationId: invalidateWindows + description: Invalidates the success rate calculation windows for a specific ID + tags: + - Success Rate + parameters: + - name: x-tenant-id + in: header + required: true + schema: + type: string + example: public + - name: x-profile-id + in: header + required: true + schema: + type: string + example: pro_WX0giXQnzk2wQJjkKVBX + - name: x-api-key + in: header + required: true + schema: + type: string + example: dev_VLzQTxkPq3ALj2mlfiHL4mMtXca4uplOIOLaKEzmWAmNBXZjwsuv5bCLjnf0QYHm + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/InvalidateWindowsRequest" + responses: + "200": + description: Windows invalidated successfully + content: + application/json: + schema: + $ref: "#/components/schemas/InvalidateWindowsResponse" + "400": + description: Invalid request parameters + "500": + description: Internal server error + + /success_rate.SuccessRateCalculator/FetchEntityAndGlobalSuccessRate: + post: + summary: Fetch entity and global success rates + operationId: fetchEntityAndGlobalSuccessRate + description: Calculates success rates for both entity-specific and global metrics + tags: + - Success Rate + parameters: + - name: x-tenant-id + in: header + required: true + schema: + type: string + example: public + - name: x-profile-id + in: header + required: true + schema: + type: string + example: pro_WX0giXQnzk2wQJjkKVBX + - name: x-api-key + in: header + required: true + schema: + type: string + example: dev_VLzQTxkPq3ALj2mlfiHL4mMtXca4uplOIOLaKEzmWAmNBXZjwsuv5bCLjnf0QYHm + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CalGlobalSuccessRateRequest" + responses: + "200": + description: Success rates calculated successfully + content: + application/json: + schema: + $ref: "#/components/schemas/CalGlobalSuccessRateResponse" + "400": + description: Invalid request parameters + "500": + description: Internal server error + + /elimination.EliminationAnalyser/GetEliminationStatus: + post: + summary: Fetch eliminated processor list + operationId: GetEliminationStatus + description: Determines which processors should be eliminated from routing consideration based on historical performance data. + tags: + - Elimination + parameters: + - name: x-tenant-id + in: header + required: true + schema: + type: string + example: public + - name: x-profile-id + in: header + required: true + schema: + type: string + example: pro_WX0giXQnzk2wQJjkKVBX + - name: x-api-key + in: header + required: true + schema: + type: string + example: dev_VLzQTxkPq3ALj2mlfiHL4mMtXca4uplOIOLaKEzmWAmNBXZjwsuv5bCLjnf0QYHm + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/EliminationRequest" + example: + id: "merchant1" + params: "card" + labels: ["stripe", "adyen"] + config: + bucket_size: 5 + bucket_leak_interval_in_secs: 10 + responses: + "200": + description: Returns a eliminated processor list + content: + application/json: + schema: + $ref: "#/components/schemas/EliminationResponse" + "400": + description: Invalid request parameters + "500": + description: Internal server error + + /elimination.EliminationAnalyser/UpdateEliminationBucket: + post: + summary: Update elimination bucket + operationId: UpdateEliminationBucket + description: Updates the failure records for specific processors, affecting future elimination decisions. + tags: + - Elimination + parameters: + - name: x-tenant-id + in: header + required: true + schema: + type: string + example: public + - name: x-profile-id + in: header + required: true + schema: + type: string + example: pro_WX0giXQnzk2wQJjkKVBX + - name: x-api-key + in: header + required: true + schema: + type: string + example: dev_VLzQTxkPq3ALj2mlfiHL4mMtXca4uplOIOLaKEzmWAmNBXZjwsuv5bCLjnf0QYHm + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateEliminationBucketRequest" + example: + id: "merchant1" + params: "card" + labels_with_bucket_name: + [{ "label": "stripe", "bucket_name": "bucket1" }] + config: + bucket_size: 5 + bucket_leak_interval_in_secs: 10 + responses: + "200": + description: Bucket updated successfully + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateEliminationBucketResponse" + "400": + description: Invalid request parameters + "500": + description: Internal server error + + /elimination.EliminationAnalyser/InvalidateBucket: + post: + summary: Invalidate elimination bucket + operationId: InvalidateBucket + description: Invalidates all elimination bucket data for a specific entity, effectively resetting its processor elimination history. + tags: + - Elimination + parameters: + - name: x-tenant-id + in: header + required: true + schema: + type: string + example: public + - name: x-profile-id + in: header + required: true + schema: + type: string + example: pro_WX0giXQnzk2wQJjkKVBX + - name: x-api-key + in: header + required: true + schema: + type: string + example: dev_VLzQTxkPq3ALj2mlfiHL4mMtXca4uplOIOLaKEzmWAmNBXZjwsuv5bCLjnf0QYHm + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/InvalidateBucketRequest" + responses: + "200": + description: Buckets invalidated successfully + content: + application/json: + schema: + $ref: "#/components/schemas/InvalidateBucketResponse" + "400": + description: Invalid request parameters + "500": + description: Internal server error + +components: + schemas: + LabelWithScoreList: + type: object + properties: + score: + type: number + format: double + example: 100.0 + description: Calculated success rate score + label: + type: string + example: stripe + description: Label identifier + required: + - score + - label + + LabelWithScore: + type: array + items: + $ref: "#/components/schemas/LabelWithScoreList" + example: + - score: 100.0 + label: stripe + - score: 98.5 + label: adyen + + LabelWithStatusList: + type: object + properties: + status: + type: number + format: boolean + example: true + description: Labels terminal status + label: + type: string + example: stripe + description: Label identifier + required: + - status + - label + + LabelWithStatus: + type: array + items: + $ref: "#/components/schemas/LabelWithStatusList" + example: + - status: false + label: stripe + - status: true + label: adyen + + CalSuccessRateRequest: + type: object + properties: + id: + type: string + description: Entity identifier + params: + type: string + description: Parameters on which success rate scores has to be maintained + labels: + type: array + items: + type: string + description: Labels for which to calculate success rates + required: + - id + - params + - labels + + CalSuccessRateResponse: + type: object + properties: + labels_with_score: + type: array + items: + $ref: "#/components/schemas/LabelWithScore" + description: List of labels with their calculated success rates + + UpdateSuccessRateWindowRequest: + type: object + properties: + id: + type: string + example: merchant1 + description: Entity identifier + params: + type: string + example: card + description: Additional parameters for window update + labels_with_status: + type: array + items: + $ref: "#/components/schemas/LabelWithStatus" + description: Entity-specific labels with their success/failure status + global_labels_with_status: + type: array + items: + $ref: "#/components/schemas/LabelWithStatus" + description: Global labels with their success/failure status + required: + - id + - params + - labels_with_status + + UpdateSuccessRateWindowResponse: + type: object + properties: + status: + type: string + enum: [WINDOW_UPDATION_SUCCEEDED, WINDOW_UPDATION_FAILED] + description: Status of the window update operation + required: + - status + + InvalidateWindowsRequest: + type: object + properties: + id: + type: string + example: merchant1 + description: Entity identifier for which to invalidate windows + required: + - id + + InvalidateWindowsResponse: + type: object + properties: + status: + type: string + enum: [WINDOW_INVALIDATION_SUCCEEDED, WINDOW_INVALIDATION_FAILED] + description: Status of the window invalidation operation + required: + - status + + CalGlobalSuccessRateRequest: + type: object + properties: + entity_id: + type: string + example: merchant1 + description: Entity identifier + entity_params: + type: string + example: card + description: Additional parameters for entity success rate calculation + entity_labels: + type: array + example: ["stripe", "adyen"] + items: + type: string + description: Entity-specific labels for which to calculate success rates + global_labels: + type: array + example: ["stripe", "adyen"] + items: + type: string + description: Global labels for which to calculate success rates + required: + - entity_id + - entity_params + - entity_labels + - global_labels + + CalGlobalSuccessRateResponse: + type: object + properties: + entity_scores_with_labels: + type: array + items: + $ref: "#/components/schemas/LabelWithScore" + description: Entity-specific labels with their calculated success rates + global_scores_with_labels: + type: array + items: + $ref: "#/components/schemas/LabelWithScore" + description: Global labels with their calculated success rates + + EliminationRequest: + type: object + properties: + id: + type: string + description: Entity identifier + params: + type: string + description: AAdditional parameters for elimination analysis + labels: + type: array + items: + type: string + description: Labels (processors) to check for elimination + config: + $ref: "#/components/schemas/EliminationBucketConfig" + required: + - id + - labels + - config + + EliminationBucketConfig: + type: object + properties: + bucket_size: + type: integer + format: uint64 + description: Maximum failures allowed before elimination + bucket_leak_interval_in_secs: + type: number + format: uint64 + description: Time interval after which failures are "forgotten" + required: + - bucket_size + - bucket_leak_interval_in_secs + + EliminationResponse: + type: object + properties: + labels_with_score: + type: array + items: + $ref: "#/components/schemas/LabelWithStatus" + description: Elimination status for each label + + EliminationInformation: + type: object + properties: + entity: + $ref: "#/components/schemas/BucketInformation" + global: + $ref: "#/components/schemas/BucketInformation" + + BucketInformation: + type: object + properties: + is_eliminated: + type: boolean + example: true + description: Whether the processor should be eliminated + bucket_name: + type: array + items: + type: string + description: Bucket identifiers that triggered elimination + + UpdateEliminationBucketRequest: + type: object + properties: + id: + type: string + description: "Entity identifier" + params: + type: string + description: "Additional parameters" + labels_with_bucket_name: + type: array + items: + type: object + properties: + label: + type: string + description: "Processor identifier" + bucket_name: + type: string + description: "Bucket to update (failure type)" + config: + $ref: "#/components/schemas/EliminationBucketConfig" + required: + - id + - labels_with_bucket_name + - config + + LabelWithBucketName: + type: object + properties: + label: + type: string + description: "Processor identifier" + bucket_name: + type: string + description: "Bucket to update (failure type)" + required: + - label + - bucket_name + + UpdateEliminationBucketResponse: + type: object + properties: + status: + type: string + description: "Status of the update operation" + enum: + - BUCKET_UPDATION_SUCCEEDED + - BUCKET_UPDATION_FAILED + required: + - status + + InvalidateBucketRequest: + type: object + properties: + id: + type: string + example: merchant1 + description: "Entity identifier to invalidate the bucket" + required: + - id + + InvalidateBucketResponse: + type: object + properties: + status: + type: string + description: "Status of the invalidate operation" + enum: + - BUCKET_INVALIDATION_SUCCEEDED + - BUCKET_INVALIDATION_FAILED + required: + - status diff --git a/api-reference/intelligent-router-api-reference/elimination/fetch-eliminated-processor-list.mdx b/api-reference/intelligent-router-api-reference/elimination/fetch-eliminated-processor-list.mdx new file mode 100644 index 00000000000..a99b041479a --- /dev/null +++ b/api-reference/intelligent-router-api-reference/elimination/fetch-eliminated-processor-list.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /elimination.EliminationAnalyser/GetEliminationStatus +--- \ No newline at end of file diff --git a/api-reference/intelligent-router-api-reference/elimination/invalidate-elimination-bucket.mdx b/api-reference/intelligent-router-api-reference/elimination/invalidate-elimination-bucket.mdx new file mode 100644 index 00000000000..34edbb72e3d --- /dev/null +++ b/api-reference/intelligent-router-api-reference/elimination/invalidate-elimination-bucket.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /elimination.EliminationAnalyser/InvalidateBucket +--- \ No newline at end of file diff --git a/api-reference/intelligent-router-api-reference/elimination/update-elimination-bucket.mdx b/api-reference/intelligent-router-api-reference/elimination/update-elimination-bucket.mdx new file mode 100644 index 00000000000..2cb8d09867f --- /dev/null +++ b/api-reference/intelligent-router-api-reference/elimination/update-elimination-bucket.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /elimination.EliminationAnalyser/UpdateEliminationBucket +--- \ No newline at end of file diff --git a/api-reference/intelligent-router-api-reference/overview.mdx b/api-reference/intelligent-router-api-reference/overview.mdx new file mode 100644 index 00000000000..316e6799b36 --- /dev/null +++ b/api-reference/intelligent-router-api-reference/overview.mdx @@ -0,0 +1,111 @@ +# Dynamo - Dynamic Routing System + +## Overview + +Dynamo is an open-source dynamic routing system designed for payment processing. It intelligently routes payments to different processors based on real-time metrics, helping to optimize payment flows and increase transaction success rates. + +## Why Dynamo? + +- 💸 **Increase Payment Success**: Automatically route to the best-performing processors +- 📊 **Data-Driven Decisions**: Make routing choices based on real performance metrics +- 🌐 **Multi-tenant Support**: Isolate routing data between different merchants +- ⚡ **High Performance**: Built with Rust for maximum efficiency and reliability +- 🔄 **Multiple Routing Strategies**: Choose from success-rate, elimination, or contract-based routing + +## Documentation + +- [Integration Guide](https://github.com/juspay/hyperswitch-intelligent-router/blob/main/docs/integration-guide.md) +- [Installation Guide](https://github.com/juspay/hyperswitch-intelligent-router/blob/main/docs/installation.md) +- [Configuration Guide](https://github.com/juspay/hyperswitch-intelligent-router/blob/main/docs/configuration.md) +- [API Reference](https://api-reference.hyperswitch.io/intelligent-router-api-reference/overview) +- [Contributing Guidelines](https://github.com/juspay/hyperswitch-intelligent-router/blob/main/CONTRIBUTING.md) + +## Quick Start + +### Local Setup + +```bash +# Clone the repository +git clone https://github.com/yourusername/dynamo.git +cd dynamo + +# Configure Redis +# Make sure Redis is running on localhost:6379 or update the config file + +# Build the core service +cargo build --release + +# Run with development configuration +./target/release/dynamo +``` + +### Docker Setup + +```bash +# Clone the repository +git clone https://github.com/yourusername/dynamo.git +cd dynamo + +# Build the Docker image +docker build -t dynamo:latest . + +# Run with default configuration +docker run -p 8000:8000 -p 9000:9000 dynamo:latest + +# Run with custom configuration +docker run -p 8000:8000 -p 9000:9000 -v $(pwd)/config:/app/config dynamo:latest +``` + +## Usage Examples + +### Success Rate Based Routing + +```bash +# Make a routing decision based on success rates +grpcurl -d '{"id": "merchant1", "params": "card", "labels": ["stripe", "adyen"], "config": {"min_aggregates_size": 5, "default_success_rate": 100}}' \ + -plaintext localhost:8000 success_rate.SuccessRateCalculator/FetchSuccessRate +``` + +### Update Payment Results + +```bash +# Update success rate data with payment results +grpcurl -d '{"id": "merchant1", "params": "card", "labels_with_status": [{"label": "stripe", "status": true}], "config": {"max_aggregates_size": 10, "current_block_threshold": {"max_total_count": 5}}}' \ + -plaintext localhost:8000 success_rate.SuccessRateCalculator/UpdateSuccessRateWindow +``` + +For more examples, see our [Examples Documentation](docs/examples.md). + +## Project Structure + +Dynamo consists of two main components: + +- **dynamo**: Core routing service with GRPC/HTTP APIs +- **procesmo**: WebAssembly module for data processing and visualization + +The project uses a workspace structure: + +``` +crates/ +├── dynamo/ # Main routing service +└── procesmo/ # WebAssembly data processing module +``` + +## Contributing + +We welcome contributions from everyone! Here's how you can help: + +1. Fork the repository +2. Create your feature branch: `git checkout -b feature/amazing-feature` +3. Commit your changes: `git commit -m 'Add some amazing feature'` +4. Push to your branch: `git push origin feature/amazing-feature` +5. Open a Pull Request + +See [https://github.com/juspay/hyperswitch-intelligent-router/blob/main/CONTRIBUTING.md](https://github.com/juspay/hyperswitch-intelligent-router/blob/main/CONTRIBUTING.md) for detailed guidelines. + +## Community + +- Join our [Discord server](https://discord.gg/wJZ7DVW8mm) for discussions +- Join our [Slack channel](https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw) +- Report issues on [GitHub Issues](https://github.com/juspay/hyperswitch-dynamo/issues) +- Follow updates on [Twitter](https://twitter.com/juspay) \ No newline at end of file diff --git a/api-reference/intelligent-router-api-reference/success-rate/fetch-entity-and-global-success-rates.mdx b/api-reference/intelligent-router-api-reference/success-rate/fetch-entity-and-global-success-rates.mdx new file mode 100644 index 00000000000..882b95e71c1 --- /dev/null +++ b/api-reference/intelligent-router-api-reference/success-rate/fetch-entity-and-global-success-rates.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /success_rate.SuccessRateCalculator/FetchEntityAndGlobalSuccessRate +--- \ No newline at end of file diff --git a/api-reference/intelligent-router-api-reference/success-rate/fetch-success-rate-for-an-entity.mdx b/api-reference/intelligent-router-api-reference/success-rate/fetch-success-rate-for-an-entity.mdx new file mode 100644 index 00000000000..ad6bebae3d0 --- /dev/null +++ b/api-reference/intelligent-router-api-reference/success-rate/fetch-success-rate-for-an-entity.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /success_rate.SuccessRateCalculator/FetchSuccessRate +--- \ No newline at end of file diff --git a/api-reference/intelligent-router-api-reference/success-rate/invalidate-windows.mdx b/api-reference/intelligent-router-api-reference/success-rate/invalidate-windows.mdx new file mode 100644 index 00000000000..0fcc1026254 --- /dev/null +++ b/api-reference/intelligent-router-api-reference/success-rate/invalidate-windows.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /success_rate.SuccessRateCalculator/InvalidateWindows +--- \ No newline at end of file diff --git a/api-reference/intelligent-router-api-reference/success-rate/update-success-rate-window.mdx b/api-reference/intelligent-router-api-reference/success-rate/update-success-rate-window.mdx new file mode 100644 index 00000000000..28206a88c20 --- /dev/null +++ b/api-reference/intelligent-router-api-reference/success-rate/update-success-rate-window.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /success_rate.SuccessRateCalculator/UpdateSuccessRateWindow +--- \ No newline at end of file diff --git a/api-reference/mint.json b/api-reference/mint.json index e74a8f1386a..077b111eaaa 100644 --- a/api-reference/mint.json +++ b/api-reference/mint.json @@ -32,6 +32,10 @@ { "name": "Locker API Reference", "url": "locker-api-reference" + }, + { + "name": "Intelligent Router API Reference", + "url": "intelligent-router-api-reference" } ], "navigation": [ @@ -278,6 +282,32 @@ ] } ] + }, + { + "group": "Hyperswitch Intelligent Router", + "pages": ["intelligent-router-api-reference/overview"] + }, + { + "group": "API Reference", + "pages": [ + { + "group": "Success Rate", + "pages": [ + "intelligent-router-api-reference/success-rate/fetch-success-rate-for-an-entity", + "intelligent-router-api-reference/success-rate/update-success-rate-window", + "intelligent-router-api-reference/success-rate/invalidate-windows", + "intelligent-router-api-reference/success-rate/fetch-entity-and-global-success-rates" + ] + }, + { + "group": "Elimination", + "pages": [ + "intelligent-router-api-reference/elimination/fetch-eliminated-processor-list", + "intelligent-router-api-reference/elimination/update-elimination-bucket", + "intelligent-router-api-reference/elimination/invalidate-elimination-bucket" + ] + } + ] } ], "footerSocials": {
2025-04-04T13:25:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [x] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Open API reference for Intelligent router ### 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="1728" alt="image" src="https://github.com/user-attachments/assets/7df6c90a-a125-4dfb-aa36-6072881ecc23" /> ## 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.113.0
961c875ecc225c924160448f01bf38a8e5a4ca03
961c875ecc225c924160448f01bf38a8e5a4ca03
juspay/hyperswitch
juspay__hyperswitch-7729
Bug: refactor(postman): update `Stripe` response `status`, `error_code`, and `error_message` for deprecated `Sofort` Map `status`, `error_code`, and `error_message` for `Stripe` Payment Processor `Sofort` Bank Transfer Payment Method as `Sofort` has been deprecated by `Stripe`.
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js index aa8d32b0cf2..c2e29faee5a 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Confirm/event.test.js @@ -63,21 +63,21 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "requires_customer_action" for "status" +// Response body should have value "failed" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'", + "[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'failed'", function () { - pm.expect(jsonData.status).to.eql("requires_customer_action"); + pm.expect(jsonData.status).to.eql("failed"); }, ); } -// Response body should have "next_action.redirect_to_url" +// Response body should have "next_action" pm.test( - "[POST]::/payments - Content check if 'next_action.redirect_to_url' exists", + "[POST]::/payments - Content check if 'next_action' exists", function () { - pm.expect(typeof jsonData.next_action.redirect_to_url !== "undefined").to.be + pm.expect(typeof jsonData.next_action !== "undefined").to.be .true; }, ); @@ -92,6 +92,26 @@ if (jsonData?.payment_method_type) { ); } +// Response body should have value "payment_method_not_available" for "error_code" +if (jsonData?.error_code) { + pm.test( + "[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'payment_method_not_available'", + function () { + pm.expect(jsonData.error_code).to.eql("payment_method_not_available"); + }, + ); +} + +// Response body should have value "Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort" for "error_message" +if (jsonData?.error_message) { + pm.test( + "[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort'", + function () { + pm.expect(jsonData.error_message).to.eql("Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort"); + }, + ); +} + // Response body should have value "stripe" for "connector" if (jsonData?.connector) { pm.test( diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js index 9053ddab13b..e99ef624bf2 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario16-Bank Redirect-sofort/Payments - Retrieve/event.test.js @@ -60,12 +60,32 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "requires_customer_action" for "status" +// Response body should have value "failed" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'", + "[POST]::/payments:id - Content check if value for 'status' matches 'failed'", function () { - pm.expect(jsonData.status).to.eql("requires_customer_action"); + pm.expect(jsonData.status).to.eql("failed"); }, ); } + +// Response body should have value "payment_method_not_available" for "error_code" +if (jsonData?.error_code) { + pm.test( + "[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'payment_method_not_available'", + function () { + pm.expect(jsonData.error_code).to.eql("payment_method_not_available"); + }, + ); +} + +// Response body should have value "Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort" for "error_message" +if (jsonData?.error_message) { + pm.test( + "[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort'", + function () { + pm.expect(jsonData.error_message).to.eql("Sofort is deprecated and can no longer be used for payment acceptance. Please refer to https://docs.stripe.com/payments/sofort"); + }, + ); +} \ No newline at end of file
2025-04-04T15:28:17Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> Mapping `status`, `error_code`, and `error_message` for `Stripe` Payment Processor `Sofort` Bank Transfer Payment Method as `Sofort` has been deprecated by `Stripe`. ### 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). --> `Stripe` Payment Processor has deprecated `Sofort` Bank Transfer Payment Method. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> _Before_ <img width="1728" alt="image" src="https://github.com/user-attachments/assets/96c27305-04fb-4839-a91b-84ed69bc4ced" /> _After_ <img width="1727" alt="image" src="https://github.com/user-attachments/assets/50881bf2-8fb0-4b7f-8a96-2742e55d6c76" /> ## 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.113.0
961c875ecc225c924160448f01bf38a8e5a4ca03
961c875ecc225c924160448f01bf38a8e5a4ca03
juspay/hyperswitch
juspay__hyperswitch-7725
Bug: [FEATURE] Add refunds update flow in v2 apis Add refunds update flow in v2 apis
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index c6b6f01fb0a..12c30cc61f0 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3265,6 +3265,64 @@ ] } }, + "/v2/refunds/{id}/update_metadata": { + "put": { + "tags": [ + "Refunds" + ], + "summary": "Refunds - Metadata Update", + "description": "Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields", + "operationId": "Update Refund Metadata and Reason", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "The identifier for refund", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RefundMetadataUpdateRequest" + }, + "examples": { + "Update refund reason": { + "value": { + "reason": "Paid by mistake" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Refund updated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RefundResponse" + } + } + } + }, + "400": { + "description": "Missing Mandatory fields" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/v2/refunds/{id}": { "get": { "tags": [ @@ -20629,6 +20687,24 @@ } } }, + "RefundMetadataUpdateRequest": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive", + "example": "Customer returned the product", + "nullable": true, + "maxLength": 255 + }, + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "nullable": true + } + }, + "additionalProperties": false + }, "RefundResponse": { "type": "object", "required": [ @@ -20737,24 +20813,6 @@ "instant" ] }, - "RefundUpdateRequest": { - "type": "object", - "properties": { - "reason": { - "type": "string", - "description": "An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive", - "example": "Customer returned the product", - "nullable": true, - "maxLength": 255 - }, - "metadata": { - "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", - "nullable": true - } - }, - "additionalProperties": false - }, "RefundsCreateRequest": { "type": "object", "required": [ diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index bb20978e0d2..e556c7eccce 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -166,6 +166,19 @@ pub struct RefundUpdateRequest { pub metadata: Option<pii::SecretSerdeValue>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct RefundMetadataUpdateRequest { + /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive + #[schema(max_length = 255, example = "Customer returned the product")] + pub reason: Option<String>, + + /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] + pub metadata: Option<pii::SecretSerdeValue>, +} + #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundManualUpdateRequest { diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 95b6c3d7df9..6057797e200 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -148,6 +148,7 @@ Never share your secret api keys. Keep them guarded and secure. //Routes for refunds routes::refunds::refunds_create, + routes::refunds::refunds_metadata_update, routes::refunds::refunds_retrieve, routes::refunds::refunds_list, @@ -193,7 +194,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::refunds::RefundType, api_models::refunds::RefundResponse, api_models::refunds::RefundStatus, - api_models::refunds::RefundUpdateRequest, + api_models::refunds::RefundMetadataUpdateRequest, api_models::organization::OrganizationCreateRequest, api_models::organization::OrganizationUpdateRequest, api_models::organization::OrganizationResponse, diff --git a/crates/openapi/src/routes/refunds.rs b/crates/openapi/src/routes/refunds.rs index 8fb6d4f1835..6628d432203 100644 --- a/crates/openapi/src/routes/refunds.rs +++ b/crates/openapi/src/routes/refunds.rs @@ -112,6 +112,7 @@ pub async fn refunds_retrieve_with_body() {} operation_id = "Update a Refund", security(("api_key" = [])) )] +#[cfg(feature = "v1")] pub async fn refunds_update() {} /// Refunds - List @@ -215,6 +216,38 @@ pub async fn refunds_filter_list() {} #[cfg(feature = "v2")] pub async fn refunds_create() {} +/// Refunds - Metadata Update +/// +/// Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields +#[utoipa::path( + put, + path = "/v2/refunds/{id}/update_metadata", + params( + ("id" = String, Path, description = "The identifier for refund") + ), + request_body( + content = RefundMetadataUpdateRequest, + examples( + ( + "Update refund reason" = ( + value = json!({ + "reason": "Paid by mistake" + }) + ) + ) + ) + ), + responses( + (status = 200, description = "Refund updated", body = RefundResponse), + (status = 400, description = "Missing Mandatory fields") + ), + tag = "Refunds", + operation_id = "Update Refund Metadata and Reason", + security(("api_key" = [])) +)] +#[cfg(feature = "v2")] +pub async fn refunds_metadata_update() {} + /// Refunds - Retrieve /// /// Retrieves a Refund. This may be used to get the status of a previously initiated refund diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs index 8d113d5a329..ee10e1b3081 100644 --- a/crates/router/src/core/refunds_v2.rs +++ b/crates/router/src/core/refunds_v2.rs @@ -465,6 +465,42 @@ where request.check_integrity(request, connector_refund_id.to_owned()) } +// ********************************************** REFUND UPDATE ********************************************** + +pub async fn refund_metadata_update_core( + state: SessionState, + merchant_account: domain::MerchantAccount, + req: refunds::RefundMetadataUpdateRequest, + global_refund_id: id_type::GlobalRefundId, +) -> errors::RouterResponse<refunds::RefundResponse> { + let db = state.store.as_ref(); + let refund = db + .find_refund_by_id(&global_refund_id, merchant_account.storage_scheme) + .await + .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; + + let response = db + .update_refund( + refund, + storage::RefundUpdate::MetadataAndReasonUpdate { + metadata: req.metadata, + reason: req.reason, + updated_by: merchant_account.storage_scheme.to_string(), + }, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!( + "Unable to update refund with refund_id: {}", + global_refund_id.get_string_repr() + ) + })?; + + refunds::RefundResponse::foreign_try_from(response).map(services::ApplicationResponse::Json) +} + // ********************************************** REFUND SYNC ********************************************** #[instrument(skip_all)] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index db65dff64b5..9cb83192f6f 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1187,7 +1187,11 @@ impl Refunds { { route = route .service(web::resource("").route(web::post().to(refunds::refunds_create))) - .service(web::resource("/{id}").route(web::get().to(refunds::refunds_retrieve))); + .service(web::resource("/{id}").route(web::get().to(refunds::refunds_retrieve))) + .service( + web::resource("/{id}/update_metadata") + .route(web::put().to(refunds::refunds_metadata_update)), + ); } route diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index dc92545841e..1ae4412807c 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -12,6 +12,39 @@ use crate::{ services::{api, authentication as auth, authorization::permissions::Permission}, types::{api::refunds, domain}, }; + +#[cfg(feature = "v2")] +/// A private module to hold internal types to be used in route handlers. +/// This is because we will need to implement certain traits on these types which will have the resource id +/// But the api payload will not contain the resource id +/// So these types can hold the resource id along with actual api payload, on which api event and locking action traits can be implemented +mod internal_payload_types { + use super::*; + + // Serialize is implemented because of api events + #[derive(Debug, serde::Serialize)] + pub struct RefundsGenericRequestWithResourceId<T: serde::Serialize> { + pub global_refund_id: common_utils::id_type::GlobalRefundId, + pub payment_id: Option<common_utils::id_type::GlobalPaymentId>, + #[serde(flatten)] + pub payload: T, + } + + impl<T: serde::Serialize> common_utils::events::ApiEventMetric + for RefundsGenericRequestWithResourceId<T> + { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + let refund_id = self.global_refund_id.clone(); + self.payment_id + .clone() + .map(|payment_id| common_utils::events::ApiEventsType::Refund { + payment_id, + refund_id, + }) + } + } +} + /// Refunds - Create /// /// To create a refund against an already processed payment @@ -323,6 +356,45 @@ pub async fn refunds_update( .await } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))] +pub async fn refunds_metadata_update( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<refunds::RefundMetadataUpdateRequest>, + path: web::Path<common_utils::id_type::GlobalRefundId>, +) -> HttpResponse { + let flow = Flow::RefundsUpdate; + + let global_refund_id = path.into_inner(); + let internal_payload = internal_payload_types::RefundsGenericRequestWithResourceId { + global_refund_id: global_refund_id.clone(), + payment_id: None, + payload: json_payload.into_inner(), + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + internal_payload, + |state, auth: auth::AuthenticationData, req, _| { + refund_metadata_update_core( + state, + auth.merchant_account, + req.payload, + global_refund_id.clone(), + ) + }, + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), diff --git a/crates/router/src/types/api/refunds.rs b/crates/router/src/types/api/refunds.rs index 935cb14c1f7..908d8cddaf4 100644 --- a/crates/router/src/types/api/refunds.rs +++ b/crates/router/src/types/api/refunds.rs @@ -1,11 +1,11 @@ #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] pub use api_models::refunds::RefundRequest; -#[cfg(all(feature = "v2", feature = "refunds_v2"))] -pub use api_models::refunds::RefundsCreateRequest; pub use api_models::refunds::{ RefundListRequest, RefundListResponse, RefundResponse, RefundStatus, RefundType, RefundUpdateRequest, RefundsRetrieveBody, RefundsRetrieveRequest, }; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +pub use api_models::refunds::{RefundMetadataUpdateRequest, RefundsCreateRequest}; pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync}; pub use hyperswitch_interfaces::api::refunds::{Refund, RefundExecute, RefundSync};
2025-04-04T13:18:14Z
## 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 contains refunds update flow for v2 apis. It is a part of v2 implementation of refunds. ### 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). --> Merging this pr will add refunds update flow to the hyperswitch v2 apis, merchants can update refunds with v2 apis. ## 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 Refund API Call ``` curl --location 'http://localhost:8080/v2/refunds' \ --header 'X-Profile-Id: pro_AL59Mhfn1eDbm5FtUXao' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_t3GJeRLga4fvpMYfeA26gnjD5jwPWUFA9gbGdUfRwujMbWd54GDi5YjhcbmL5WiQ' \ --data '{ "payment_id":"12345_pay_01966ca5ba0f781394e31ca377c045c1", "merchant_reference_id":"1745579609", "reason":"Paid by mistake", "metadata":{ "foo":"bar" } }' ``` - Response from the above call ``` { "id": "12345_ref_01966ca5cdd87781af1426c620531fb5", "payment_id": "12345_pay_01966ca5ba0f781394e31ca377c045c1", "merchant_reference_id": "1745579528", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-04-25T11:12:07.651Z", "updated_at": "2025-04-25T11:12:08.717Z", "connector": "stripe", "profile_id": "pro_AL59Mhfn1eDbm5FtUXao", "merchant_connector_id": "mca_rAbIwlE7su9DkFILFzSO", "connector_refund_reference_id": null } ``` - Update Refund API Call ``` curl --location --request PUT 'http://localhost:8080/v2/refunds/12345_ref_01966ca5cdd87781af1426c620531fb5/update_metadata' \ --header 'x-profile-id: pro_AL59Mhfn1eDbm5FtUXao' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_t3GJeRLga4fvpMYfeA26gnjD5jwPWUFA9gbGdUfRwujMbWd54GDi5YjhcbmL5WiQ' \ --data '{ "reason":"Customer asked for refund", "metadata": { "customer": "Mr bean from IIT Dholakpur" } }' ``` - Response from the above call ``` { "id": "12345_ref_01966ca5cdd87781af1426c620531fb5", "payment_id": "12345_pay_01966ca5ba0f781394e31ca377c045c1", "merchant_reference_id": "1745579528", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Customer asked for refund", "metadata": { "customer": "Mr bean from IIT Dholakpur" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-04-25T11:12:07.651Z", "updated_at": "2025-04-25T11:12:10.581Z", "connector": "stripe", "profile_id": "pro_AL59Mhfn1eDbm5FtUXao", "merchant_connector_id": "mca_rAbIwlE7su9DkFILFzSO", "connector_refund_reference_id": null } ``` ## 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.114.0
c6c57c1c52ad3ec08e8d443e49227950e390965e
c6c57c1c52ad3ec08e8d443e49227950e390965e
juspay/hyperswitch
juspay__hyperswitch-7732
Bug: FEATURE(connector): [Facilitapay] Add support for Pix Bank transfer Documentation: https://sandbox-portal.facilitapay.com/#/docs
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 10682866ab7..c758e0fbb8a 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -6230,6 +6230,18 @@ "description": "CNPJ is a Brazilian company tax identification number", "example": "74469027417312", "nullable": true + }, + "source_bank_account_id": { + "type": "string", + "description": "Source bank account number", + "example": "8b2812f0-d6c8-4073-97bb-9fa964d08bc5", + "nullable": true + }, + "destination_bank_account_id": { + "type": "string", + "description": "Destination bank account number", + "example": "9b95f84e-de61-460b-a14b-f23b4e71c97b", + "nullable": true } } } @@ -7776,6 +7788,7 @@ "dlocal", "ebanx", "elavon", + "facilitapay", "fiserv", "fiservemea", "fiuu", @@ -10443,6 +10456,18 @@ "user_bank_account_number" ] }, + { + "type": "string", + "enum": [ + "user_source_bank_account_id" + ] + }, + { + "type": "string", + "enum": [ + "user_destination_bank_account_id" + ] + }, { "type": "string", "enum": [ @@ -19428,6 +19453,18 @@ "description": "Partially masked CNPJ - CNPJ is a Brazilian company tax identification number", "example": "**** 417312", "nullable": true + }, + "source_bank_account_id": { + "type": "string", + "description": "Partially masked source bank account number", + "example": "********-****-4073-****-9fa964d08bc5", + "nullable": true + }, + "destination_bank_account_id": { + "type": "string", + "description": "Partially masked destination bank account number", + "example": "********-****-460b-****-f23b4e71c97b", + "nullable": true } } }, @@ -21082,6 +21119,7 @@ "dlocal", "ebanx", "elavon", + "facilitapay", "fiserv", "fiservemea", "fiuu", diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index dafeaf65c03..1df7b395e1f 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -8321,6 +8321,18 @@ "description": "CNPJ is a Brazilian company tax identification number", "example": "74469027417312", "nullable": true + }, + "source_bank_account_id": { + "type": "string", + "description": "Source bank account number", + "example": "8b2812f0-d6c8-4073-97bb-9fa964d08bc5", + "nullable": true + }, + "destination_bank_account_id": { + "type": "string", + "description": "Destination bank account number", + "example": "9b95f84e-de61-460b-a14b-f23b4e71c97b", + "nullable": true } } } @@ -9826,6 +9838,7 @@ "dlocal", "ebanx", "elavon", + "facilitapay", "fiserv", "fiservemea", "fiuu", @@ -12640,6 +12653,18 @@ "user_bank_account_number" ] }, + { + "type": "string", + "enum": [ + "user_source_bank_account_id" + ] + }, + { + "type": "string", + "enum": [ + "user_destination_bank_account_id" + ] + }, { "type": "string", "enum": [ @@ -23809,6 +23834,18 @@ "description": "Partially masked CNPJ - CNPJ is a Brazilian company tax identification number", "example": "**** 417312", "nullable": true + }, + "source_bank_account_id": { + "type": "string", + "description": "Partially masked source bank account number", + "example": "********-****-4073-****-9fa964d08bc5", + "nullable": true + }, + "destination_bank_account_id": { + "type": "string", + "description": "Partially masked destination bank account number", + "example": "********-****-460b-****-f23b4e71c97b", + "nullable": true } } }, @@ -25573,6 +25610,7 @@ "dlocal", "ebanx", "elavon", + "facilitapay", "fiserv", "fiservemea", "fiuu", diff --git a/config/config.example.toml b/config/config.example.toml index 15b9dd2fc4d..63c7c89b039 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -331,7 +331,7 @@ cards = [ "datatrans", "deutschebank", "digitalvirgo", - "facilitapay", + "facilitapay", "globalpay", "globepay", "gocardless", @@ -647,6 +647,9 @@ credit = { country = "FR", currency = "CAD, AUD, EUR, USD" } [pm_filters.digitalvirgo] direct_carrier_billing = {country = "MA, CM, ZA, EG, SN, DZ, TN, ML, GN, GH, LY, GA, CG, MG, BW, SD, NG, ID, SG, AZ, TR, FR, ES, PL, GB, PT, DE, IT, BE, IE, SK, GR, NL, CH, BR, MX, AR, CL, AE, IQ, KW, BH, SA, QA, PS, JO, OM, RU" , currency = "MAD, XOF, XAF, ZAR, EGP, DZD, TND, GNF, GHS, LYD, XAF, CDF, MGA, BWP, SDG, NGN, IDR, SGD, RUB, AZN, TRY, EUR, PLN, GBP, CHF, BRL, MXN, ARS, CLP, AED, IQD, KWD, BHD, SAR, QAR, ILS, JOD, OMR" } +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } @@ -745,7 +748,7 @@ credit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,B debit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } [connector_customer] -connector_list = "gocardless,stax,stripe" +connector_list = "gocardless,stax,stripe,facilitapay" payout_connector_list = "nomupay,stripe,wise" [bank_config.online_banking_fpx] diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 802af333f8b..0b4c0967e14 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -166,7 +166,7 @@ force_cookies = true enabled = true [connector_customer] -connector_list = "gocardless,stax,stripe" +connector_list = "gocardless,stax,stripe,facilitapay" payout_connector_list = "nomupay,stripe,wise" [delayed_session_response] @@ -359,6 +359,9 @@ paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,N credit.currency = "USD" debit.currency = "USD" +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 3cc5b8c0f8a..563941cf9d0 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -15,7 +15,7 @@ open_banking_uk.adyen.banks = "aib,bank_of_scotland,danske_bank,first_direct,fir przelewy24.stripe.banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,banki_spbdzielcze,blik,bnp_paribas,boz,citi,credit_agricole,e_transfer_pocztowy24,getin_bank,idea_bank,inteligo,mbank_mtransfer,nest_przelew,noble_pay,pbac_z_ipko,plus_bank,santander_przelew24,toyota_bank,volkswagen_bank" [connector_customer] -connector_list = "stax,stripe,gocardless" +connector_list = "stax,stripe,gocardless,facilitapay" payout_connector_list = "nomupay,stripe,wise" # Connector configuration, provided attributes will be used to fulfill API requests. @@ -409,6 +409,9 @@ paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,N credit.currency = "USD" debit.currency = "USD" +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index c3555f7ea05..c861ade9aab 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -15,7 +15,7 @@ open_banking_uk.adyen.banks = "aib,bank_of_scotland,danske_bank,first_direct,fir przelewy24.stripe.banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,banki_spbdzielcze,blik,bnp_paribas,boz,citi,credit_agricole,e_transfer_pocztowy24,getin_bank,idea_bank,inteligo,mbank_mtransfer,nest_przelew,noble_pay,pbac_z_ipko,plus_bank,santander_przelew24,toyota_bank,volkswagen_bank" [connector_customer] -connector_list = "stax,stripe,gocardless" +connector_list = "stax,stripe,gocardless,facilitapay" payout_connector_list = "nomupay,stripe,wise" # Connector configuration, provided attributes will be used to fulfill API requests. @@ -411,6 +411,9 @@ paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,N credit.currency = "USD" debit.currency = "USD" +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } diff --git a/config/development.toml b/config/development.toml index 37c496efbae..f271f70fcac 100644 --- a/config/development.toml +++ b/config/development.toml @@ -574,6 +574,9 @@ paypal = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,B [pm_filters.braintree] paypal = { currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD" } +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } @@ -751,7 +754,7 @@ nexixpay = { payment_method = "card" } redsys = { payment_method = "card" } [connector_customer] -connector_list = "gocardless,stax,stripe" +connector_list = "gocardless,stax,stripe,facilitapay" payout_connector_list = "nomupay,stripe,wise" [dummy_connector] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 4b0214b8f1b..d8f2d4bd34d 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -575,6 +575,9 @@ apple_pay = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,B google_pay = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,BS,BW,BY,BZ,CA,CD,CH,CL,CN,CO,CR,CU,CY,CZ,DE,DJ,DK,DO,DZ,EE,EG,ET,ES,FI,FJ,FR,GB,GE,GH,GI,GM,GR,GT,GY,HK,HN,HR,HU,ID,IE,IL,IN,IS,IT,JM,JO,JP,KE,KH,KR,KW,KY,KZ,LB,LK,LT,LV,LY,MA,MC,MD,ME,MG,MK,MN,MO,MT,MV,MW,MX,MY,NG,NI,NO,NP,NL,NZ,OM,PA,PE,PG,PH,PK,PL,PT,PY,QA,RO,RS,RU,RW,SA,SB,SC,SE,SG,SH,SI,SK,SL,SO,SM,SR,ST,SV,SY,TH,TJ,TN,TO,TR,TW,TZ,UA,UG,US,UY,UZ,VE,VA,VN,VU,WS,CF,AG,DM,GD,KN,LC,VC,YE,ZA,ZM", currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,GBP,GEL,GHS,GIP,GMD,GTQ,GYD,HKD,HNL,HRK,HUF,IDR,ILS,INR,ISK,JMD,JOD,JPY,KES,KHR,KRW,KWD,KYD,KZT,LBP,LKR,LYD,MAD,MDL,MGA,MKD,MNT,MOP,MVR,MWK,MXN,MYR,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STN,SVC,SYP,THB,TJS,TND,TOP,TRY,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,YER,ZAR,ZMW"} paypal = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,BS,BW,BY,BZ,CA,CD,CH,CL,CN,CO,CR,CU,CY,CZ,DE,DJ,DK,DO,DZ,EE,EG,ET,ES,FI,FJ,FR,GB,GE,GH,GI,GM,GR,GT,GY,HK,HN,HR,HU,ID,IE,IL,IN,IS,IT,JM,JO,JP,KE,KH,KR,KW,KY,KZ,LB,LK,LT,LV,LY,MA,MC,MD,ME,MG,MK,MN,MO,MT,MV,MW,MX,MY,NG,NI,NO,NP,NL,NZ,OM,PA,PE,PG,PH,PK,PL,PT,PY,QA,RO,RS,RU,RW,SA,SB,SC,SE,SG,SH,SI,SK,SL,SO,SM,SR,ST,SV,SY,TH,TJ,TN,TO,TR,TW,TZ,UA,UG,US,UY,UZ,VE,VA,VN,VU,WS,CF,AG,DM,GD,KN,LC,VC,YE,ZA,ZM", currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,GBP,GEL,GHS,GIP,GMD,GTQ,GYD,HKD,HNL,HRK,HUF,IDR,ILS,INR,ISK,JMD,JOD,JPY,KES,KHR,KRW,KWD,KYD,KZT,LBP,LKR,LYD,MAD,MDL,MGA,MKD,MNT,MOP,MVR,MWK,MXN,MYR,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STN,SVC,SYP,THB,TJS,TND,TOP,TRY,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,YER,ZAR,ZMW"} +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.helcim] credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } @@ -713,7 +716,7 @@ card.debit = { connector_list = "cybersource" } connector_list = "adyen,cybersource,novalnet,stripe,worldpay" [connector_customer] -connector_list = "gocardless,stax,stripe" +connector_list = "gocardless,stax,stripe,facilitapay" payout_connector_list = "nomupay,stripe,wise" diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 212504baaa3..55857ec4412 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -237,6 +237,8 @@ pub enum FieldType { UserBlikCode, UserBank, UserBankAccountNumber, + UserSourceBankAccountId, + UserDestinationBankAccountId, Text, DropDown { options: Vec<String> }, UserDateOfBirth, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 011fd7e4431..1f7b40de7e0 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -19,6 +19,7 @@ use common_utils::{ ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, + new_type::MaskedBankAccount, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; @@ -3413,6 +3414,14 @@ pub enum BankTransferData { /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, + + /// Source bank account number + #[schema(value_type = Option<String>, example = "8b2812f0-d6c8-4073-97bb-9fa964d08bc5")] + source_bank_account_id: Option<MaskedBankAccount>, + + /// Destination bank account number + #[schema(value_type = Option<String>, example = "9b95f84e-de61-460b-a14b-f23b4e71c97b")] + destination_bank_account_id: Option<MaskedBankAccount>, }, Pse {}, LocalBankTransfer { diff --git a/crates/api_models/src/payments/additional_info.rs b/crates/api_models/src/payments/additional_info.rs index 33297e2b342..371bebe5982 100644 --- a/crates/api_models/src/payments/additional_info.rs +++ b/crates/api_models/src/payments/additional_info.rs @@ -167,6 +167,14 @@ pub struct PixBankTransferAdditionalData { /// Partially masked CNPJ - CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "**** 417312")] pub cnpj: Option<MaskedBankAccount>, + + /// Partially masked source bank account number + #[schema(value_type = Option<String>, example = "********-****-4073-****-9fa964d08bc5")] + pub source_bank_account_id: Option<MaskedBankAccount>, + + /// Partially masked destination bank account number + #[schema(value_type = Option<String>, example = "********-****-460b-****-f23b4e71c97b")] + pub destination_bank_account_id: Option<MaskedBankAccount>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 70efd457a97..0b831d63c2d 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -80,7 +80,7 @@ pub enum RoutableConnectors { Dlocal, Ebanx, Elavon, - // Facilitapay, + Facilitapay, Fiserv, Fiservemea, Fiuu, @@ -225,7 +225,7 @@ pub enum Connector { Dlocal, Ebanx, Elavon, - // Facilitapay, + Facilitapay, Fiserv, Fiservemea, Fiuu, @@ -344,6 +344,7 @@ impl Connector { | (Self::Iatapay, _) | (Self::Volt, _) | (Self::Itaubank, _) + | (Self::Facilitapay, _) ) } pub fn supports_file_storage_module(self) -> bool { @@ -387,7 +388,7 @@ impl Connector { | Self::Dlocal | Self::Ebanx | Self::Elavon - // | Self::Facilitapay + | Self::Facilitapay | Self::Fiserv | Self::Fiservemea | Self::Fiuu @@ -537,7 +538,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Dlocal => Self::Dlocal, RoutableConnectors::Ebanx => Self::Ebanx, RoutableConnectors::Elavon => Self::Elavon, - // RoutableConnectors::Facilitapay => Self::Facilitapay, + RoutableConnectors::Facilitapay => Self::Facilitapay, RoutableConnectors::Fiserv => Self::Fiserv, RoutableConnectors::Fiservemea => Self::Fiservemea, RoutableConnectors::Fiuu => Self::Fiuu, @@ -646,7 +647,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Dlocal => Ok(Self::Dlocal), Connector::Ebanx => Ok(Self::Ebanx), Connector::Elavon => Ok(Self::Elavon), - // Connector::Facilitapay => Ok(Self::Facilitapay), + Connector::Facilitapay => Ok(Self::Facilitapay), Connector::Fiserv => Ok(Self::Fiserv), Connector::Fiservemea => Ok(Self::Fiservemea), Connector::Fiuu => Ok(Self::Fiuu), diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 87c64747c69..48aa9eafd8f 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -6607,6 +6607,66 @@ pub enum RomaniaStatesAbbreviation { ValceaCounty, } +#[derive( + Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString, +)] +pub enum BrazilStatesAbbreviation { + #[strum(serialize = "AC")] + Acre, + #[strum(serialize = "AL")] + Alagoas, + #[strum(serialize = "AP")] + Amapá, + #[strum(serialize = "AM")] + Amazonas, + #[strum(serialize = "BA")] + Bahia, + #[strum(serialize = "CE")] + Ceará, + #[strum(serialize = "DF")] + DistritoFederal, + #[strum(serialize = "ES")] + EspíritoSanto, + #[strum(serialize = "GO")] + Goiás, + #[strum(serialize = "MA")] + Maranhão, + #[strum(serialize = "MT")] + MatoGrosso, + #[strum(serialize = "MS")] + MatoGrossoDoSul, + #[strum(serialize = "MG")] + MinasGerais, + #[strum(serialize = "PA")] + Pará, + #[strum(serialize = "PB")] + Paraíba, + #[strum(serialize = "PR")] + Paraná, + #[strum(serialize = "PE")] + Pernambuco, + #[strum(serialize = "PI")] + Piauí, + #[strum(serialize = "RJ")] + RioDeJaneiro, + #[strum(serialize = "RN")] + RioGrandeDoNorte, + #[strum(serialize = "RS")] + RioGrandeDoSul, + #[strum(serialize = "RO")] + Rondônia, + #[strum(serialize = "RR")] + Roraima, + #[strum(serialize = "SC")] + SantaCatarina, + #[strum(serialize = "SP")] + SãoPaulo, + #[strum(serialize = "SE")] + Sergipe, + #[strum(serialize = "TO")] + Tocantins, +} + #[derive( Clone, Copy, diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 782ca4cb711..70bfe9befac 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -196,7 +196,7 @@ pub struct ConnectorConfig { pub dlocal: Option<ConnectorTomlConfig>, pub ebanx_payout: Option<ConnectorTomlConfig>, pub elavon: Option<ConnectorTomlConfig>, - // pub facilitapay: Option<ConnectorTomlConfig>, + pub facilitapay: Option<ConnectorTomlConfig>, pub fiserv: Option<ConnectorTomlConfig>, pub fiservemea: Option<ConnectorTomlConfig>, pub fiuu: Option<ConnectorTomlConfig>, @@ -373,7 +373,7 @@ impl ConnectorConfig { Connector::Dlocal => Ok(connector_data.dlocal), Connector::Ebanx => Ok(connector_data.ebanx_payout), Connector::Elavon => Ok(connector_data.elavon), - // Connector::Facilitapay => Ok(connector_data.facilitapay), + Connector::Facilitapay => Ok(connector_data.facilitapay), Connector::Fiserv => Ok(connector_data.fiserv), Connector::Fiservemea => Ok(connector_data.fiservemea), Connector::Fiuu => Ok(connector_data.fiuu), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 5675ad1d766..9ba3e86cac8 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -5828,3 +5828,10 @@ type="Text" api_key="Merchant ID" key1="Terminal ID" api_secret="Secret Key" + +[facilitapay] +[[facilitapay.bank_transfer]] + payment_method_type = "pix" +[facilitapay.connector_auth.Bodykey] + api_key="Password" + key1="Username" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index efc797a5a1e..da0fd93f70f 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -4353,3 +4353,10 @@ payment_method_type = "UnionPay" api_key = "Merchant ID" key1 = "Terminal ID" api_secret = "Secret Key" + +[facilitapay] +[[facilitapay.bank_transfer]] + payment_method_type = "pix" +[facilitapay.connector_auth.Bodykey] + api_key="Password" + key1="Username" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 4aa34446cbd..a2bdf1863bb 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -5800,3 +5800,10 @@ payment_method_type = "UnionPay" api_key = "Merchant ID" key1 = "Terminal ID" api_secret = "Secret Key" + +[facilitapay] +[[facilitapay.bank_transfer]] + payment_method_type = "pix" +[facilitapay.connector_auth.Bodykey] + api_key="Password" + key1="Username" diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay.rs index 7f0ed1a2f09..9b1a6486df4 100644 --- a/crates/hyperswitch_connectors/src/connectors/facilitapay.rs +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay.rs @@ -1,28 +1,37 @@ +mod requests; +mod responses; pub mod transformers; +use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, - types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, + types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ - router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_data::{AccessToken, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, - payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + payments::{ + Authorize, Capture, CreateConnectorCustomer, PSync, PaymentMethodToken, Session, + SetupMandate, Void, + }, refunds::{Execute, RSync}, }, router_request_types::{ - AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, - RefundsData, SetupMandateRequestData, + AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, + PaymentsSyncData, RefundsData, SetupMandateRequestData, + }, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ - PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, - RefundSyncRouterData, RefundsRouterData, + ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -33,27 +42,41 @@ use hyperswitch_interfaces::{ configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, - types::{self, Response}, + types::{self, RefreshTokenType, Response}, webhooks, }; -use masking::{ExposeInterface, Mask}; -use transformers as facilitapay; +use lazy_static::lazy_static; +use masking::{Mask, PeekInterface}; +use requests::{ + FacilitapayAuthRequest, FacilitapayCustomerRequest, FacilitapayPaymentsRequest, + FacilitapayRefundRequest, FacilitapayRouterData, +}; +use responses::{ + FacilitapayAuthResponse, FacilitapayCustomerResponse, FacilitapayPaymentsResponse, + FacilitapayRefundResponse, +}; +use transformers::parse_facilitapay_error_response; -use crate::{constants::headers, types::ResponseRouterData, utils}; +use crate::{ + constants::headers, + types::{RefreshTokenRouterData, ResponseRouterData}, + utils::{self, RefundsRequestData}, +}; #[derive(Clone)] pub struct Facilitapay { - amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Facilitapay { pub fn new() -> &'static Self { &Self { - amount_converter: &StringMinorUnitForConnector, + amount_converter: &StringMajorUnitForConnector, } } } +impl api::ConnectorCustomer for Facilitapay {} impl api::Payment for Facilitapay {} impl api::PaymentSession for Facilitapay {} impl api::ConnectorAccessToken for Facilitapay {} @@ -82,13 +105,23 @@ where req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - self.get_content_type().to_string().into(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) + let access_token = req + .access_token + .clone() + .ok_or(errors::ConnectorError::FailedToObtainAuthType)?; + + let headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + ), + ( + headers::AUTHORIZATION.to_string(), + format!("Bearer {}", access_token.token.clone().peek()).into_masked(), + ), + ]; + + Ok(headers) } } @@ -99,9 +132,6 @@ impl ConnectorCommon for Facilitapay { fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base - // TODO! Check connector documentation, on which unit they are processing the currency. - // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, - // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { @@ -112,58 +142,201 @@ impl ConnectorCommon for Facilitapay { connectors.facilitapay.base_url.as_ref() } - fn get_auth_header( + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + parse_facilitapay_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> + for Facilitapay +{ + fn get_headers( &self, - auth_type: &ConnectorAuthType, + req: &ConnectorCustomerRouterData, + connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - let auth = facilitapay::FacilitapayAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), - )]) + self.build_headers(req, connectors) } - fn build_error_response( + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( &self, - res: Response, + _req: &ConnectorCustomerRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/subject/people", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &ConnectorCustomerRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = FacilitapayCustomerRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &ConnectorCustomerRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::ConnectorCustomerType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::ConnectorCustomerType::get_headers( + self, req, connectors, + )?) + .set_body(types::ConnectorCustomerType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &ConnectorCustomerRouterData, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: facilitapay::FacilitapayErrorResponse = res + res: Response, + ) -> CustomResult<ConnectorCustomerRouterData, errors::ConnectorError> + where + ConnectorCustomerRouterData: Clone, + { + let response: FacilitapayCustomerResponse = res .response - .parse_struct("FacilitapayErrorResponse") + .parse_struct("FacilitapayCustomerResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(ErrorResponse { - status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, - attempt_status: None, - connector_transaction_id: None, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, }) } -} -impl ConnectorValidation for Facilitapay { - //TODO: implement functions when support enabled + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } +impl ConnectorValidation for Facilitapay {} + impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Facilitapay { //TODO: implement sessions flow } -impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Facilitapay {} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Facilitapay { + fn get_headers( + &self, + _req: &RefreshTokenRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + Ok(vec![( + headers::CONTENT_TYPE.to_string(), + self.common_get_content_type().to_string().into(), + )]) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefreshTokenRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/sign_in", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &RefreshTokenRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = FacilitapayAuthRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RefreshTokenRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .attach_default_headers() + .headers(RefreshTokenType::get_headers(self, req, connectors)?) + .url(&RefreshTokenType::get_url(self, req, connectors)?) + .set_body(RefreshTokenType::get_request_body(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RefreshTokenRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> { + let response: FacilitapayAuthResponse = res + .response + .parse_struct("FacilitapayAuthResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Facilitapay { + fn build_request( + &self, + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented( + "Setup Mandate flow for Facilitapay".to_string(), + ) + .into()) + } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Facilitapay { @@ -182,9 +355,9 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData fn get_url( &self, _req: &PaymentsAuthorizeRouterData, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!("{}/transactions", self.base_url(connectors))) } fn get_request_body( @@ -198,9 +371,9 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req.request.currency, )?; - let connector_router_data = facilitapay::FacilitapayRouterData::from((amount, req)); - let connector_req = - facilitapay::FacilitapayPaymentsRequest::try_from(&connector_router_data)?; + let connector_router_data = FacilitapayRouterData::from((amount, req)); + let connector_req = FacilitapayPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } @@ -232,12 +405,14 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: facilitapay::FacilitapayPaymentsResponse = res + let response: FacilitapayPaymentsResponse = res .response - .parse_struct("Facilitapay PaymentsAuthorizeResponse") + .parse_struct("FacilitapayPaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -269,10 +444,19 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Fac fn get_url( &self, - _req: &PaymentsSyncRouterData, - _connectors: &Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_transaction_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}/transactions/{}", + self.base_url(connectors), + connector_transaction_id + )) } fn build_request( @@ -296,12 +480,14 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Fac event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: facilitapay::FacilitapayPaymentsResponse = res + let response: FacilitapayPaymentsResponse = res .response - .parse_struct("facilitapay PaymentsSyncResponse") + .parse_struct("FacilitapayPaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -373,9 +559,9 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { - let response: facilitapay::FacilitapayPaymentsResponse = res + let response: FacilitapayPaymentsResponse = res .response - .parse_struct("Facilitapay PaymentsCaptureResponse") + .parse_struct("FacilitapayPaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -412,10 +598,14 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilit fn get_url( &self, - _req: &RefundsRouterData<Execute>, - _connectors: &Connectors, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!( + "{}/transactions/{}/refund_received_transaction", + self.base_url(connectors), + req.request.connector_transaction_id + )) } fn get_request_body( @@ -429,9 +619,8 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilit req.request.currency, )?; - let connector_router_data = facilitapay::FacilitapayRouterData::from((refund_amount, req)); - let connector_req = - facilitapay::FacilitapayRefundRequest::try_from(&connector_router_data)?; + let connector_router_data = FacilitapayRouterData::from((refund_amount, req)); + let connector_req = FacilitapayRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -460,9 +649,9 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilit event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: facilitapay::RefundResponse = res + let response: FacilitapayRefundResponse = res .response - .parse_struct("facilitapay RefundResponse") + .parse_struct("FacilitapayRefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -497,10 +686,16 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Facilitap fn get_url( &self, - _req: &RefundSyncRouterData, - _connectors: &Connectors, + req: &RefundSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let refund_id = req.request.get_connector_refund_id()?; + Ok(format!( + "{}/transactions/{}/refund_received_transaction/{}", + self.base_url(connectors), + req.request.connector_transaction_id, + refund_id + )) } fn build_request( @@ -514,9 +709,6 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Facilitap .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) - .set_body(types::RefundSyncType::get_request_body( - self, req, connectors, - )?) .build(), )) } @@ -527,9 +719,9 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Facilitap event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: facilitapay::RefundResponse = res + let response: FacilitapayRefundResponse = res .response - .parse_struct("facilitapay RefundSyncResponse") + .parse_struct("FacilitapayRefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -573,4 +765,48 @@ impl webhooks::IncomingWebhook for Facilitapay { } } -impl ConnectorSpecifications for Facilitapay {} +lazy_static! { + static ref FACILITAPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: + "Facilitapay", + description: + "FacilitaPay, the best and most reliable payment provider for your international business.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + static ref FACILITAPAY_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { + let facilitapay_supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut facilitapay_supported_payment_methods = SupportedPaymentMethods::new(); + + facilitapay_supported_payment_methods.add( + enums::PaymentMethod::BankTransfer, + enums::PaymentMethodType::Pix, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + refunds: common_enums::FeatureStatus::Supported, + supported_capture_methods: facilitapay_supported_capture_methods.clone(), + specific_features: None, + }, + ); + + facilitapay_supported_payment_methods + }; + static ref FACILITAPAY_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); +} + +impl ConnectorSpecifications for Facilitapay { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&*FACILITAPAY_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*FACILITAPAY_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&*FACILITAPAY_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs new file mode 100644 index 00000000000..29c2f34f332 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs @@ -0,0 +1,150 @@ +use common_enums::CountryAlpha2; +use common_utils::{new_type::MaskedBankAccount, pii, types::StringMajorUnit}; +use masking::Secret; +use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; + +pub struct FacilitapayRouterData<T> { + pub amount: StringMajorUnit, + pub router_data: T, +} + +#[derive(Debug, Serialize)] +pub struct FacilitapayAuthRequest { + pub user: FacilitapayCredentials, +} + +#[derive(Debug, Serialize)] +pub struct FacilitapayCredentials { + pub username: Secret<String>, // email_id + pub password: Secret<String>, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct FacilitapayCardDetails { + #[serde(rename = "card_number")] + pub number: cards::CardNumber, + #[serde(rename = "card_expiration_date")] + pub expiry_date: Secret<String>, // Format: "MM/YYYY" + #[serde(rename = "card_security_code")] + pub cvc: Secret<String>, + #[serde(rename = "card_brand")] + pub brand: String, + pub fullname: Secret<String>, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct CardTransactionRequest { + pub currency: api_models::enums::Currency, + pub exchange_currency: api_models::enums::Currency, + pub value: StringMajorUnit, + pub from_credit_card: FacilitapayCardDetails, + pub to_bank_account_id: Secret<String>, // UUID + pub subject_id: String, // UUID +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct PixTransactionRequest { + pub subject_id: Secret<String>, // Customer ID (UUID) + pub from_bank_account_id: MaskedBankAccount, // UUID + pub to_bank_account_id: MaskedBankAccount, // UUID + pub currency: api_models::enums::Currency, + pub exchange_currency: api_models::enums::Currency, + pub value: StringMajorUnit, + pub use_dynamic_pix: bool, + #[serde(default, with = "common_utils::custom_serde::iso8601")] + pub dynamic_pix_expires_at: PrimitiveDateTime, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(untagged)] +pub enum FacilitapayTransactionRequest { + #[allow(dead_code)] + Card(CardTransactionRequest), + Pix(PixTransactionRequest), +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct FacilitapayPaymentsRequest { + pub transaction: FacilitapayTransactionRequest, +} + +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct FacilitapayRefundRequest { + pub amount: StringMajorUnit, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct FacilitapayCustomerRequest { + pub person: FacilitapayPerson, +} + +#[derive(Debug, Serialize, Clone, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum DocumentType { + /// CC is the Cedula de Ciudadania, is a 10-digit number, which is the national identity card for Colombian citizens. + /// It is used for citizen identification purposes. + #[serde(rename = "cc")] + CedulaDeCiudadania, + /// CNPJ stands for Cadastro Nacional da Pessoa Jurídica, is a 14-digit number, + /// which is the national registry of legal entities in Brazil used as a unique identifier for Brazilian companies. + #[serde(rename = "cnpj")] + CadastroNacionaldaPessoaJurídica, + /// CPF stands for Cadastro de Pessoas Físicas, is a 11-digit number, + /// which is the national registry of natural persons in Brazil used as a unique identifier for Brazilian citizens. + #[serde(rename = "cpf")] + CadastrodePessoasFísicas, + /// CURP stands for Clave Única de Registro de Población,is a 18-digit number used as a unique identifier for Mexican citizens. + /// It is used to track tax information and other identification purposes by the government. + #[serde(rename = "curp")] + ClaveÚnicadeRegistrodePoblación, + /// NIT is the Número de Identificación Tributaria, is a 10-digit number, which is the tax identification number in Colombia. Used for companies. + #[serde(rename = "nit")] + NúmerodeIdentificaciónTributaria, + /// Passport is the travel document usually issued by a country's government + Passport, + /// RFC stands for Registro Federal de Contribuyentes, is a 13-digit number used as a unique identifier for Mexican companies. + #[serde(rename = "rfc")] + RegistroFederaldeContribuyentes, + /// RUT stands for Rol Unico Tributario, is a 9-digit number used as a unique identifier for Chilean citizens and companies. + #[serde(rename = "rut")] + RolUnicoTributario, + /// A Taxpayer Identification Number is an identifying number used for tax purposes + TaxId, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct FacilitapayPerson { + pub document_number: Secret<String>, + pub document_type: DocumentType, + pub social_name: Secret<String>, + pub fiscal_country: CountryAlpha2, + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option<pii::Email>, + #[serde(skip_serializing_if = "Option::is_none")] + pub birth_date: Option<time::Date>, + #[serde(skip_serializing_if = "Option::is_none")] + pub phone_country_code: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub phone_area_code: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub phone_number: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_city: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_state: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_complement: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_country: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_number: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_postal_code: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub address_street: Option<Secret<String>>, + pub net_monthly_average_income: Option<StringMajorUnit>, +} diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs new file mode 100644 index 00000000000..dfa01402ce9 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs @@ -0,0 +1,217 @@ +use common_utils::{pii, types::StringMajorUnit}; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use super::requests::DocumentType; + +// Response body for POST /sign_in +#[derive(Debug, Deserialize, Serialize)] +pub struct FacilitapayAuthResponse { + username: Secret<String>, + name: Secret<String>, + pub jwt: Secret<String>, +} + +#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum SubjectKycStatus { + // Customer is able to send/receive money through the platform. No action is needed on your side. + Approved, + + // Customer is required to upload documents or uploaded documents have been rejected by KYC. + Reproved, + + // Customer has uploaded KYC documents but awaiting analysis from the backoffice. No action is needed on your side. + WaitingApproval, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub struct FacilitapaySubject { + pub social_name: Secret<String>, + pub document_type: DocumentType, + pub document_number: Secret<String>, + // In documentation, both CountryAlpha2 and String are used. We cannot rely on CountryAlpha2. + pub fiscal_country: String, + pub updated_at: Option<String>, + pub status: SubjectKycStatus, + #[serde(rename = "id")] + pub customer_id: Secret<String>, + pub birth_date: Option<time::Date>, + pub email: Option<pii::Email>, + pub phone_country_code: Option<Secret<String>>, + pub phone_area_code: Option<Secret<String>>, + pub phone_number: Option<Secret<String>>, + pub address_street: Option<Secret<String>>, + pub address_number: Option<Secret<String>>, + pub address_complement: Option<Secret<String>>, + pub address_city: Option<String>, + pub address_state: Option<String>, + pub address_postal_code: Option<Secret<String>>, + pub address_country: Option<String>, + pub address_neighborhood: Option<Secret<String>>, + pub net_monthly_average_income: Option<StringMajorUnit>, + pub clearance_level: Option<i32>, + pub required_clearance_level: Option<i32>, + pub inserted_at: Option<String>, + pub references: Option<Vec<serde_json::Value>>, + pub rfc_pf: Option<Secret<String>>, // 13-digit RFC, specific to Mexico users + pub documents: Option<Vec<serde_json::Value>>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct FacilitapayCustomerResponse { + pub data: FacilitapaySubject, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PixInfo { + #[serde(rename = "type")] + pub key_type: String, + pub key: Secret<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct CreditCardResponseInfo { + pub id: String, + pub status: Option<String>, + pub document_type: String, + pub document_number: Secret<String>, + pub birthdate: Option<String>, + pub phone_country_code: Option<String>, + pub phone_area_code: Option<String>, + pub phone_number: Option<Secret<String>>, + pub inserted_at: Option<String>, +} + +// PaymentsResponse +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +#[derive(strum::Display)] +pub enum FacilitapayPaymentStatus { + /// Transaction has been created but it is waiting for an incoming TED/Wire. + /// This is the first recorded status in production mode. + #[default] + Pending, + /// Incoming TED/Wire has been identified into Facilita´s bank account. + /// When it is a deposit into an internal bank account and there is no + /// conversion involved (BRL to BRL for instance), that is the final state. + Identified, + /// The conversion rate has been closed and therefore the exchanged value + /// is defined - when it is a deposit into an internal bank account, that is the final state. + Exchanged, + /// The exchanged value has been wired to its destination (a real bank account) - that is also a final state. + Wired, + /// When for any reason the transaction cannot be concluded or need to be reversed, it is canceled. + #[serde(rename = "canceled")] + Cancelled, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct FacilitapayPaymentsResponse { + pub data: TransactionData, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct OwnerCompany { + pub social_name: Option<Secret<String>>, + #[serde(rename = "id")] + pub company_id: Option<String>, + pub document_type: DocumentType, + pub document_number: Secret<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct BankInfo { + pub swift: Option<Secret<String>>, + pub name: Option<String>, + #[serde(rename = "id")] + pub bank_id: Secret<String>, + pub code: Option<Secret<String>>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct BankAccountDetail { + pub routing_number: Option<Secret<String>>, + pub pix_info: Option<PixInfo>, + pub owner_name: Option<Secret<String>>, + pub owner_document_number: Option<Secret<String>>, + pub owner_company: Option<OwnerCompany>, + pub internal: Option<bool>, + pub intermediary_bank_account: Option<Secret<String>>, + pub intermediary_bank_account_id: Option<Secret<String>>, + #[serde(rename = "id")] + pub bank_account_id: Secret<String>, + pub iban: Option<Secret<String>>, + pub flow_type: Option<String>, + pub currency: api_models::enums::Currency, + pub branch_number: Option<Secret<String>>, + pub branch_country: Option<String>, + pub bank: Option<BankInfo>, + pub account_type: Option<String>, + pub account_number: Option<Secret<String>>, + pub aba: Option<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct TransactionData { + #[serde(rename = "id")] + pub transaction_id: String, + pub value: StringMajorUnit, + pub status: FacilitapayPaymentStatus, + pub currency: api_models::enums::Currency, + pub exchange_currency: api_models::enums::Currency, + + // Details about the destination account (Required) + pub to_bank_account: BankAccountDetail, + + // Details about the source - mutually exclusive + pub from_credit_card: Option<CreditCardResponseInfo>, + pub from_bank_account: Option<BankAccountDetail>, // Populated for PIX + + // Subject information (customer) + pub subject_id: String, + pub subject: Option<FacilitapaySubject>, + pub subject_is_receiver: Option<bool>, + + // Source identification (potentially redundant with subject or card/bank info) + pub source_name: Secret<String>, + pub source_document_type: DocumentType, + pub source_document_number: Secret<String>, + + // Timestamps and flags + pub inserted_at: Option<String>, + pub for_exchange: Option<bool>, + pub exchange_under_request: Option<bool>, + pub estimated_value_until_exchange: Option<bool>, + pub cleared: Option<bool>, + + // PIX specific field + pub dynamic_pix_code: Option<String>, // QR code string for PIX + + // Exchange details + pub exchanged_value: Option<StringMajorUnit>, + + // Cancelation details + #[serde(rename = "canceled_reason")] + pub cancelled_reason: Option<String>, + #[serde(rename = "canceled_at")] + pub cancelled_at: Option<String>, + + // Other fields + pub bank_transaction: Option<Secret<serde_json::Value>>, + pub meta: Option<serde_json::Value>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RefundData { + #[serde(rename = "id")] + pub refund_id: String, + pub status: FacilitapayPaymentStatus, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FacilitapayRefundResponse { + pub data: RefundData, +} diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs index 81c2f752d3b..a123b4796cf 100644 --- a/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs @@ -1,31 +1,45 @@ -use common_enums::enums; -use common_utils::types::StringMinorUnit; +use api_models::payments::QrCodeInformation; +use common_enums::{enums, PaymentMethod}; +use common_utils::{ + errors::CustomResult, + ext_traits::{BytesExt, Encode}, + types::StringMajorUnit, +}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, - router_data::{ConnectorAuthType, RouterData}, + payment_method_data::{BankTransferData, PaymentMethodData}, + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, - types::{PaymentsAuthorizeRouterData, RefundsRouterData}, + types, +}; +use hyperswitch_interfaces::{ + consts, errors, events::connector_api_logs::ConnectorEvent, types::Response, }; -use hyperswitch_interfaces::errors; -use masking::Secret; -use serde::{Deserialize, Serialize}; +use masking::{ExposeInterface, Secret}; +use time::PrimitiveDateTime; +use url::Url; +use super::{ + requests::{ + DocumentType, FacilitapayAuthRequest, FacilitapayCredentials, FacilitapayCustomerRequest, + FacilitapayPaymentsRequest, FacilitapayPerson, FacilitapayRefundRequest, + FacilitapayRouterData, FacilitapayTransactionRequest, PixTransactionRequest, + }, + responses::{ + FacilitapayAuthResponse, FacilitapayCustomerResponse, FacilitapayPaymentStatus, + FacilitapayPaymentsResponse, FacilitapayRefundResponse, + }, +}; use crate::{ - types::{RefundsResponseRouterData, ResponseRouterData}, - utils::PaymentsAuthorizeRequestData, + types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData}, + utils::{is_payment_failure, missing_field_err, QrImage, RouterData as OtherRouterData}, }; +type Error = error_stack::Report<errors::ConnectorError>; -//TODO: Fill the struct with respective fields -pub struct FacilitapayRouterData<T> { - pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. - pub router_data: T, -} - -impl<T> From<(StringMinorUnit, T)> for FacilitapayRouterData<T> { - fn from((amount, item): (StringMinorUnit, T)) -> Self { - //Todo : use utils to convert the amount to the type of amount that a connector accepts +impl<T> From<(StringMajorUnit, T)> for FacilitapayRouterData<T> { + fn from((amount, item): (StringMajorUnit, T)) -> Self { Self { amount, router_data: item, @@ -33,196 +47,491 @@ impl<T> From<(StringMinorUnit, T)> for FacilitapayRouterData<T> { } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, PartialEq)] -pub struct FacilitapayPaymentsRequest { - amount: StringMinorUnit, - card: FacilitapayCard, -} - -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct FacilitapayCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, -} - -impl TryFrom<&FacilitapayRouterData<&PaymentsAuthorizeRouterData>> for FacilitapayPaymentsRequest { - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<&FacilitapayRouterData<&types::PaymentsAuthorizeRouterData>> + for FacilitapayPaymentsRequest +{ + type Error = Error; fn try_from( - item: &FacilitapayRouterData<&PaymentsAuthorizeRouterData>, + item: &FacilitapayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(req_card) => { - let card = FacilitapayCard { - number: req_card.card_number, - expiry_month: req_card.card_exp_month, - expiry_year: req_card.card_exp_year, - cvc: req_card.card_cvc, - complete: item.router_data.request.is_auto_capture()?, - }; - Ok(Self { - amount: item.amount.clone(), - card, - }) + PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data { + BankTransferData::Pix { + source_bank_account_id, + destination_bank_account_id, + .. + } => { + // Set expiry time to 15 minutes from now + let dynamic_pix_expires_at = { + let now = time::OffsetDateTime::now_utc(); + let expires_at = now + time::Duration::minutes(15); + + PrimitiveDateTime::new(expires_at.date(), expires_at.time()) + }; + + let transaction_data = + FacilitapayTransactionRequest::Pix(PixTransactionRequest { + // subject id must be generated by pre-process step and link with customer id + // might require discussions to be done + subject_id: item.router_data.get_connector_customer_id()?.into(), + from_bank_account_id: source_bank_account_id.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "source bank account id", + }, + )?, + + to_bank_account_id: destination_bank_account_id.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "destination bank account id", + }, + )?, + currency: item.router_data.request.currency, + exchange_currency: item.router_data.request.currency, + value: item.amount.clone(), + use_dynamic_pix: true, + // Format: YYYY-MM-DDThh:mm:ssZ + dynamic_pix_expires_at, + }); + + Ok(Self { + transaction: transaction_data, + }) + } + BankTransferData::AchBankTransfer {} + | BankTransferData::SepaBankTransfer {} + | BankTransferData::BacsBankTransfer {} + | BankTransferData::MultibancoBankTransfer {} + | BankTransferData::PermataBankTransfer {} + | BankTransferData::BcaBankTransfer {} + | BankTransferData::BniVaBankTransfer {} + | BankTransferData::BriVaBankTransfer {} + | BankTransferData::CimbVaBankTransfer {} + | BankTransferData::DanamonVaBankTransfer {} + | BankTransferData::MandiriVaBankTransfer {} + | BankTransferData::Pse {} + | BankTransferData::InstantBankTransfer {} + | BankTransferData::LocalBankTransfer { .. } => { + Err(errors::ConnectorError::NotImplemented( + "Selected payment method through Facilitapay".to_string(), + ) + .into()) + } + }, + PaymentMethodData::Card(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + "Selected payment method through Facilitapay".to_string(), + ) + .into()) } - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } -//TODO: Fill the struct with respective fields +// Helper to build the request from Hyperswitch Auth Type +impl FacilitapayAuthRequest { + fn from_auth_type(auth: &FacilitapayAuthType) -> Self { + Self { + user: FacilitapayCredentials { + username: auth.username.clone(), + password: auth.password.clone(), + }, + } + } +} + // Auth Struct +#[derive(Debug, Clone)] pub struct FacilitapayAuthType { - pub(super) api_key: Secret<String>, + pub(super) username: Secret<String>, + pub(super) password: Secret<String>, } impl TryFrom<&ConnectorAuthType> for FacilitapayAuthType { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = Error; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - api_key: api_key.to_owned(), + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + username: key1.to_owned(), + password: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } -// PaymentsResponse -//TODO: Append the remaining status flags -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] -pub enum FacilitapayPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, + +impl TryFrom<&RefreshTokenRouterData> for FacilitapayAuthRequest { + type Error = Error; + fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> { + let auth_type = FacilitapayAuthType::try_from(&item.connector_auth_type)?; + Ok(Self::from_auth_type(&auth_type)) + } } -impl From<FacilitapayPaymentStatus> for common_enums::AttemptStatus { - fn from(item: FacilitapayPaymentStatus) -> Self { - match item { - FacilitapayPaymentStatus::Succeeded => Self::Charged, - FacilitapayPaymentStatus::Failed => Self::Failure, - FacilitapayPaymentStatus::Processing => Self::Authorizing, +fn convert_to_document_type(document_type: &str) -> Result<DocumentType, errors::ConnectorError> { + match document_type.to_lowercase().as_str() { + "cc" => Ok(DocumentType::CedulaDeCiudadania), + "cnpj" => Ok(DocumentType::CadastroNacionaldaPessoaJurídica), + "cpf" => Ok(DocumentType::CadastrodePessoasFísicas), + "curp" => Ok(DocumentType::ClaveÚnicadeRegistrodePoblación), + "nit" => Ok(DocumentType::NúmerodeIdentificaciónTributaria), + "passport" => Ok(DocumentType::Passport), + "rfc" => Ok(DocumentType::RegistroFederaldeContribuyentes), + "rut" => Ok(DocumentType::RolUnicoTributario), + "tax_id" | "taxid" => Ok(DocumentType::TaxId), + _ => Err(errors::ConnectorError::NotSupported { + message: format!("Document type '{document_type}'"), + connector: "Facilitapay", + }), + } +} + +pub fn parse_facilitapay_error_response( + res: Response, + event_builder: Option<&mut ConnectorEvent>, +) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let status_code = res.status_code; + let response_body_bytes = res.response.clone(); + + let (message, raw_error) = + match response_body_bytes.parse_struct::<serde_json::Value>("FacilitapayErrorResponse") { + Ok(json_value) => { + event_builder.map(|i| i.set_response_body(&json_value)); + + let message = extract_message_from_json(&json_value); + ( + message, + serde_json::to_string(&json_value).unwrap_or_default(), + ) + } + Err(_) => match String::from_utf8(response_body_bytes.to_vec()) { + Ok(text) => { + event_builder.map(|i| i.set_response_body(&text)); + (text.clone(), text) + } + Err(_) => ( + "Invalid response format received".to_string(), + format!( + "Unable to parse response as JSON or UTF-8 string. Status code: {}", + status_code + ), + ), + }, + }; + + Ok(ErrorResponse { + status_code, + code: consts::NO_ERROR_CODE.to_string(), + message, + reason: Some(raw_error), + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) +} + +// Helper function to extract a readable message from JSON error +fn extract_message_from_json(json: &serde_json::Value) -> String { + if let Some(obj) = json.as_object() { + if let Some(error) = obj.get("error").and_then(|e| e.as_str()) { + return error.to_string(); + } + + if obj.contains_key("errors") { + return "Validation error occurred".to_string(); } + + if !obj.is_empty() { + return obj + .iter() + .next() + .map(|(k, v)| format!("{}: {}", k, v)) + .unwrap_or_else(|| "Unknown error".to_string()); + } + } else if let Some(s) = json.as_str() { + return s.to_string(); } + + "Unknown error format".to_string() } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct FacilitapayPaymentsResponse { - status: FacilitapayPaymentStatus, - id: String, +impl TryFrom<&types::ConnectorCustomerRouterData> for FacilitapayCustomerRequest { + type Error = Error; + fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> { + let email = item.request.email.clone(); + + let social_name = item.get_billing_full_name()?; + + let (document_type, document_number) = match item.request.payment_method_data.clone() { + PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data { + BankTransferData::Pix { cpf, .. } => { + // Extract only digits from the CPF string + let document_number = + cpf.ok_or_else(missing_field_err("cpf"))?.map(|cpf_number| { + cpf_number + .chars() + .filter(|chars| chars.is_ascii_digit()) + .collect::<String>() + }); + + let document_type = convert_to_document_type("cpf")?; + (document_type, document_number) + } + _ => { + return Err(errors::ConnectorError::NotImplemented( + "Selected payment method through Facilitapay".to_string(), + ) + .into()) + } + }, + _ => { + return Err(errors::ConnectorError::NotImplemented( + "Selected payment method through Facilitapay".to_string(), + ) + .into()) + } + }; + + let fiscal_country = item.get_billing_country()?; + + let person = FacilitapayPerson { + document_number, + document_type, + social_name, + fiscal_country, + email, + birth_date: None, + phone_country_code: None, + phone_area_code: None, + phone_number: None, + address_city: None, + address_state: None, + address_complement: None, + address_country: None, + address_number: None, + address_postal_code: None, + address_street: None, + net_monthly_average_income: None, + }; + + Ok(Self { person }) + } } -impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>> +impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayCustomerResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = Error; fn try_from( - item: ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData<F, FacilitapayCustomerResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - status: common_enums::AttemptStatus::from(item.response.status), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: None, - incremental_authorization_allowed: None, - charges: None, + response: Ok(PaymentsResponseData::ConnectorCustomerResponse { + connector_customer_id: item.response.data.customer_id.expose(), }), ..item.data }) } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct FacilitapayRefundRequest { - pub amount: StringMinorUnit, +impl From<FacilitapayPaymentStatus> for common_enums::AttemptStatus { + fn from(item: FacilitapayPaymentStatus) -> Self { + match item { + FacilitapayPaymentStatus::Pending => Self::Pending, + FacilitapayPaymentStatus::Identified + | FacilitapayPaymentStatus::Exchanged + | FacilitapayPaymentStatus::Wired => Self::Charged, + FacilitapayPaymentStatus::Cancelled => Self::Failure, + } + } } -impl<F> TryFrom<&FacilitapayRouterData<&RefundsRouterData<F>>> for FacilitapayRefundRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &FacilitapayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { +impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayAuthResponse, T, AccessToken>> + for RouterData<F, T, AccessToken> +{ + type Error = Error; + fn try_from( + item: ResponseRouterData<F, FacilitapayAuthResponse, T, AccessToken>, + ) -> Result<Self, Self::Error> { Ok(Self { - amount: item.amount.to_owned(), + response: Ok(AccessToken { + token: item.response.jwt, + expires: 86400, // Facilitapay docs say 24 hours validity. 24 * 60 * 60 = 86400 seconds. + }), + ..item.data }) } } -// Type definition for Refund Response +impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = Error; + fn try_from( + item: ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let status = if item.data.payment_method == PaymentMethod::BankTransfer + && item.response.data.status == FacilitapayPaymentStatus::Identified + { + common_enums::AttemptStatus::AuthenticationPending + } else { + common_enums::AttemptStatus::from(item.response.data.status.clone()) + }; -#[allow(dead_code)] -#[derive(Debug, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { - Succeeded, - Failed, - #[default] - Processing, + Ok(Self { + status, + response: if is_payment_failure(status) { + Err(ErrorResponse { + code: item.response.data.status.clone().to_string(), + message: item.response.data.status.clone().to_string(), + reason: item.response.data.cancelled_reason, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(item.response.data.transaction_id), + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + }) + } else { + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.data.transaction_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: get_qr_code_data(&item.response)?, + network_txn_id: None, + connector_response_reference_id: Some(item.response.data.transaction_id), + incremental_authorization_allowed: None, + charges: None, + }) + }, + ..item.data + }) + } } -impl From<RefundStatus> for enums::RefundStatus { - fn from(item: RefundStatus) -> Self { - match item { - RefundStatus::Succeeded => Self::Success, - RefundStatus::Failed => Self::Failure, - RefundStatus::Processing => Self::Pending, - //TODO: Review mapping +fn get_qr_code_data( + response: &FacilitapayPaymentsResponse, +) -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> { + let expiration_time: i64 = if let Some(meta) = &response.data.meta { + if let Some(due_date_str) = meta + .get("dynamic_pix_due_date") + .and_then(|due_date_value| due_date_value.as_str()) + { + let datetime = time::OffsetDateTime::parse( + due_date_str, + &time::format_description::well_known::Rfc3339, + ) + .map_err(|_| errors::ConnectorError::ResponseHandlingFailed)?; + + datetime.unix_timestamp() * 1000 + } else { + // If dynamic_pix_due_date isn't present, use current time + 15 minutes + let now = time::OffsetDateTime::now_utc(); + let expires_at = now + time::Duration::minutes(15); + expires_at.unix_timestamp() * 1000 } + } else { + // If meta is null, use current time + 15 minutes + let now = time::OffsetDateTime::now_utc(); + let expires_at = now + time::Duration::minutes(15); + expires_at.unix_timestamp() * 1000 + }; + + let dynamic_pix_code = response.data.dynamic_pix_code.as_ref().ok_or_else(|| { + errors::ConnectorError::MissingRequiredField { + field_name: "dynamic_pix_code", + } + })?; + + let image_data = QrImage::new_from_data(dynamic_pix_code.clone()) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + + let image_data_url = Url::parse(image_data.data.clone().as_str()) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + + let qr_code_info = QrCodeInformation::QrDataUrl { + image_data_url, + display_to_timestamp: Some(expiration_time), + }; + + Some(qr_code_info.encode_to_value()) + .transpose() + .change_context(errors::ConnectorError::ResponseHandlingFailed) +} + +impl<F> TryFrom<&FacilitapayRouterData<&types::RefundsRouterData<F>>> for FacilitapayRefundRequest { + type Error = Error; + fn try_from( + item: &FacilitapayRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.clone(), + }) } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { - id: String, - status: RefundStatus, +impl From<FacilitapayPaymentStatus> for enums::RefundStatus { + fn from(item: FacilitapayPaymentStatus) -> Self { + match item { + FacilitapayPaymentStatus::Identified + | FacilitapayPaymentStatus::Exchanged + | FacilitapayPaymentStatus::Wired => Self::Success, + FacilitapayPaymentStatus::Cancelled => Self::Failure, + FacilitapayPaymentStatus::Pending => Self::Pending, + } + } } -impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<Execute, FacilitapayRefundResponse>> + for types::RefundsRouterData<Execute> +{ + type Error = Error; fn try_from( - item: RefundsResponseRouterData<Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, FacilitapayRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + connector_refund_id: item.response.data.refund_id.to_string(), + refund_status: enums::RefundStatus::from(item.response.data.status), }), ..item.data }) } } -impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<RSync, FacilitapayRefundResponse>> + for types::RefundsRouterData<RSync> +{ + type Error = Error; fn try_from( - item: RefundsResponseRouterData<RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, FacilitapayRefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + connector_refund_id: item.response.data.refund_id.to_string(), + refund_status: enums::RefundStatus::from(item.response.data.status), }), ..item.data }) } } - -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] -pub struct FacilitapayErrorResponse { - pub status_code: u16, - pub code: String, - pub message: String, - pub reason: Option<String>, -} diff --git a/crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs index 4f6cc393fc5..0ccf5518aa9 100644 --- a/crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs @@ -65,7 +65,9 @@ impl TryFrom<&ItaubankRouterData<&types::PaymentsAuthorizeRouterData>> for Itaub match item.router_data.request.payment_method_data.clone() { PaymentMethodData::BankTransfer(bank_transfer_data) => { match *bank_transfer_data { - BankTransferData::Pix { pix_key, cpf, cnpj } => { + BankTransferData::Pix { + pix_key, cpf, cnpj, .. + } => { let nome = item.router_data.get_optional_billing_full_name(); // cpf and cnpj are mutually exclusive let devedor = match (cnpj, cpf) { diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 35d95343aba..c15da205985 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -825,7 +825,6 @@ default_imp_for_create_customer!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, - connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 41817d955a6..97ac61d6470 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -2725,6 +2725,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 60cb878d9a3..4f0c2eb8639 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -13,10 +13,10 @@ use common_enums::{ enums::{ AlbaniaStatesAbbreviation, AndorraStatesAbbreviation, AttemptStatus, AustriaStatesAbbreviation, BelarusStatesAbbreviation, BelgiumStatesAbbreviation, - BosniaAndHerzegovinaStatesAbbreviation, BulgariaStatesAbbreviation, - CanadaStatesAbbreviation, CroatiaStatesAbbreviation, CzechRepublicStatesAbbreviation, - DenmarkStatesAbbreviation, FinlandStatesAbbreviation, FranceStatesAbbreviation, - FutureUsage, GermanyStatesAbbreviation, GreeceStatesAbbreviation, + BosniaAndHerzegovinaStatesAbbreviation, BrazilStatesAbbreviation, + BulgariaStatesAbbreviation, CanadaStatesAbbreviation, CroatiaStatesAbbreviation, + CzechRepublicStatesAbbreviation, DenmarkStatesAbbreviation, FinlandStatesAbbreviation, + FranceStatesAbbreviation, FutureUsage, GermanyStatesAbbreviation, GreeceStatesAbbreviation, HungaryStatesAbbreviation, IcelandStatesAbbreviation, IrelandStatesAbbreviation, ItalyStatesAbbreviation, LatviaStatesAbbreviation, LiechtensteinStatesAbbreviation, LithuaniaStatesAbbreviation, LuxembourgStatesAbbreviation, MaltaStatesAbbreviation, @@ -5118,6 +5118,52 @@ impl ForeignTryFrom<String> for UkraineStatesAbbreviation { } } +impl ForeignTryFrom<String> for BrazilStatesAbbreviation { + type Error = error_stack::Report<errors::ConnectorError>; + + fn foreign_try_from(value: String) -> Result<Self, Self::Error> { + let state_abbreviation_check = + StringExt::<Self>::parse_enum(value.clone(), "BrazilStatesAbbreviation"); + + match state_abbreviation_check { + Ok(state_abbreviation) => Ok(state_abbreviation), + Err(_) => match value.as_str() { + "Acre" => Ok(Self::Acre), + "Alagoas" => Ok(Self::Alagoas), + "Amapá" => Ok(Self::Amapá), + "Amazonas" => Ok(Self::Amazonas), + "Bahia" => Ok(Self::Bahia), + "Ceará" => Ok(Self::Ceará), + "Distrito Federal" => Ok(Self::DistritoFederal), + "Espírito Santo" => Ok(Self::EspíritoSanto), + "Goiás" => Ok(Self::Goiás), + "Maranhão" => Ok(Self::Maranhão), + "Mato Grosso" => Ok(Self::MatoGrosso), + "Mato Grosso do Sul" => Ok(Self::MatoGrossoDoSul), + "Minas Gerais" => Ok(Self::MinasGerais), + "Pará" => Ok(Self::Pará), + "Paraíba" => Ok(Self::Paraíba), + "Paraná" => Ok(Self::Paraná), + "Pernambuco" => Ok(Self::Pernambuco), + "Piauí" => Ok(Self::Piauí), + "Rio de Janeiro" => Ok(Self::RioDeJaneiro), + "Rio Grande do Norte" => Ok(Self::RioGrandeDoNorte), + "Rio Grande do Sul" => Ok(Self::RioGrandeDoSul), + "Rondônia" => Ok(Self::Rondônia), + "Roraima" => Ok(Self::Roraima), + "Santa Catarina" => Ok(Self::SantaCatarina), + "São Paulo" => Ok(Self::SãoPaulo), + "Sergipe" => Ok(Self::Sergipe), + "Tocantins" => Ok(Self::Tocantins), + _ => Err(errors::ConnectorError::InvalidDataFormat { + field_name: "address.state", + } + .into()), + }, + } + } +} + pub trait ForeignTryFrom<F>: Sized { type Error; diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index f69b9dc6855..2d386d0f002 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -18,6 +18,7 @@ use common_utils::{ use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use time::Date; + // We need to derive Serialize and Deserialize because some parts of payment method data are being // stored in the database as serde_json::Value #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] @@ -612,6 +613,10 @@ pub enum BankTransferData { cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number cnpj: Option<Secret<String>>, + /// Source bank account UUID + source_bank_account_id: Option<MaskedBankAccount>, + /// Destination bank account UUID. + destination_bank_account_id: Option<MaskedBankAccount>, }, Pse {}, LocalBankTransfer { @@ -1450,9 +1455,19 @@ impl From<api_models::payments::BankTransferData> for BankTransferData { api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } => { Self::MandiriVaBankTransfer {} } - api_models::payments::BankTransferData::Pix { pix_key, cpf, cnpj } => { - Self::Pix { pix_key, cpf, cnpj } - } + api_models::payments::BankTransferData::Pix { + pix_key, + cpf, + cnpj, + source_bank_account_id, + destination_bank_account_id, + } => Self::Pix { + pix_key, + cpf, + cnpj, + source_bank_account_id, + destination_bank_account_id, + }, api_models::payments::BankTransferData::Pse {} => Self::Pse {}, api_models::payments::BankTransferData::LocalBankTransfer { bank_code } => { Self::LocalBankTransfer { bank_code } @@ -1478,11 +1493,19 @@ impl From<BankTransferData> for api_models::payments::additional_info::BankTrans BankTransferData::CimbVaBankTransfer {} => Self::CimbVa {}, BankTransferData::DanamonVaBankTransfer {} => Self::DanamonVa {}, BankTransferData::MandiriVaBankTransfer {} => Self::MandiriVa {}, - BankTransferData::Pix { pix_key, cpf, cnpj } => Self::Pix(Box::new( + BankTransferData::Pix { + pix_key, + cpf, + cnpj, + source_bank_account_id, + destination_bank_account_id, + } => Self::Pix(Box::new( api_models::payments::additional_info::PixBankTransferAdditionalData { pix_key: pix_key.map(MaskedBankAccount::from), cpf: cpf.map(MaskedBankAccount::from), cnpj: cnpj.map(MaskedBankAccount::from), + source_bank_account_id, + destination_bank_account_id, }, )), BankTransferData::Pse {} => Self::Pse {}, diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 2f4fb7a8013..192d45c8fce 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -189,6 +189,8 @@ enum RequiredField { PixKey, PixCnpj, PixCpf, + PixSourceBankAccountId, + PixDestinationBankAccountId, GiftCardNumber, GiftCardCvc, DcbMsisdn, @@ -782,6 +784,27 @@ impl RequiredField { value: None, }, ), + Self::PixSourceBankAccountId => ( + "payment_method_data.bank_transfer.pix.source_bank_account_id".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.bank_transfer.pix.source_bank_account_id" + .to_string(), + display_name: "source_bank_account_id".to_string(), + field_type: FieldType::UserSourceBankAccountId, + value: None, + }, + ), + Self::PixDestinationBankAccountId => ( + "payment_method_data.bank_transfer.pix.destination_bank_account_id".to_string(), + RequiredFieldInfo { + required_field: + "payment_method_data.bank_transfer.pix.destination_bank_account_id" + .to_string(), + display_name: "destination_bank_account_id".to_string(), + field_type: FieldType::UserDestinationBankAccountId, + value: None, + }, + ), Self::GiftCardNumber => ( "payment_method_data.gift_card.number".to_string(), RequiredFieldInfo { @@ -3068,6 +3091,20 @@ fn get_bank_transfer_required_fields() -> HashMap<enums::PaymentMethodType, Conn }, ), (Connector::Adyen, fields(vec![], vec![], vec![])), + ( + Connector::Facilitapay, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::from([ + RequiredField::PixSourceBankAccountId.to_tuple(), + RequiredField::PixDestinationBankAccountId.to_tuple(), + RequiredField::BillingAddressCountries(vec!["BR"]).to_tuple(), + RequiredField::BillingUserFirstName.to_tuple(), + RequiredField::BillingUserLastName.to_tuple(), + ]), + }, + ), ]), ), ( diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index c2f26b1ed9a..b00ed9a4600 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1370,10 +1370,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { elavon::transformers::ElavonAuthType::try_from(self.auth_type)?; Ok(()) } - // api_enums::Connector::Facilitapay => { - // facilitapay::transformers::FacilitapayAuthType::try_from(self.auth_type)?; - // Ok(()) - // } + api_enums::Connector::Facilitapay => { + facilitapay::transformers::FacilitapayAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Fiserv => { fiserv::transformers::FiservAuthType::try_from(self.auth_type)?; fiserv::transformers::FiservSessionObject::try_from(self.connector_meta_data)?; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index b4d3995e994..34a8fba4767 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -40,7 +40,6 @@ use error_stack::{report, ResultExt}; use events::EventInfo; use futures::future::join_all; use helpers::{decrypt_paze_token, ApplePayData}; -use hyperswitch_domain_models::payments::{payment_intent::CustomerData, ClickToPayMetaData}; #[cfg(feature = "v2")] use hyperswitch_domain_models::payments::{ PaymentCaptureData, PaymentConfirmData, PaymentIntentData, PaymentStatusData, @@ -54,6 +53,10 @@ pub use hyperswitch_domain_models::{ router_data::{PaymentMethodToken, RouterData}, router_request_types::CustomerDetails, }; +use hyperswitch_domain_models::{ + payments::{payment_intent::CustomerData, ClickToPayMetaData}, + router_data::AccessToken, +}; use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "v2")] use operations::ValidateStatusForOperation; @@ -3052,16 +3055,6 @@ where // Validating the blocklist guard and generate the fingerprint blocklist_guard(state, merchant_account, key_store, operation, payment_data).await?; - let updated_customer = call_create_connector_customer_if_required( - state, - customer, - merchant_account, - key_store, - &merchant_connector_account, - payment_data, - ) - .await?; - #[cfg(feature = "v1")] let merchant_recipient_data = if let Some(true) = payment_data .get_payment_intent() @@ -3114,6 +3107,22 @@ where &call_connector_action, ); + let updated_customer = call_create_connector_customer_if_required( + state, + customer, + merchant_account, + key_store, + &merchant_connector_account, + payment_data, + router_data.access_token.as_ref(), + ) + .await?; + + #[cfg(feature = "v1")] + if let Some(connector_customer_id) = payment_data.get_connector_customer_id() { + router_data.connector_customer = Some(connector_customer_id); + } + router_data.payment_method_token = if let Some(decrypted_token) = add_decrypted_payment_method_token(tokenization_action.clone(), payment_data).await? { @@ -4275,6 +4284,7 @@ pub async fn call_create_connector_customer_if_required<F, Req, D>( key_store: &domain::MerchantKeyStore, merchant_connector_account: &helpers::MerchantConnectorAccountType, payment_data: &mut D, + access_token: Option<&AccessToken>, ) -> RouterResult<Option<storage::CustomerUpdate>> where F: Send + Clone + Sync, @@ -4337,7 +4347,7 @@ where if should_call_connector { // Create customer at connector and update the customer table to store this data - let router_data = payment_data + let mut customer_router_data = payment_data .construct_router_data( state, connector.connector.id(), @@ -4350,7 +4360,9 @@ where ) .await?; - let connector_customer_id = router_data + customer_router_data.access_token = access_token.cloned(); + + let connector_customer_id = customer_router_data .create_connector_customer(state, &connector) .await?; @@ -8056,6 +8068,9 @@ pub trait OperationSessionGetters<F> { fn get_capture_method(&self) -> Option<enums::CaptureMethod>; fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId>; + #[cfg(feature = "v1")] + fn get_connector_customer_id(&self) -> Option<String>; + #[cfg(feature = "v1")] fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation>; @@ -8247,6 +8262,11 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> { self.vault_operation.as_ref() } + #[cfg(feature = "v1")] + fn get_connector_customer_id(&self) -> Option<String> { + self.connector_customer_id.clone() + } + // #[cfg(feature = "v2")] // fn get_capture_method(&self) -> Option<enums::CaptureMethod> { // Some(self.payment_intent.capture_method) diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index ad50919ae06..d130e0c5097 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -396,9 +396,9 @@ impl ConnectorData { enums::Connector::Elavon => { Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new()))) } - // enums::Connector::Facilitapay => { - // Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay))) - // } + enums::Connector::Facilitapay => { + Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay::new()))) + } enums::Connector::Fiserv => { Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new()))) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 54abe8f7ce9..f95d80bf0d0 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -247,7 +247,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Dlocal => Self::Dlocal, api_enums::Connector::Ebanx => Self::Ebanx, api_enums::Connector::Elavon => Self::Elavon, - // api_enums::Connector::Facilitapay => Self::Facilitapay, + api_enums::Connector::Facilitapay => Self::Facilitapay, api_enums::Connector::Fiserv => Self::Fiserv, api_enums::Connector::Fiservemea => Self::Fiservemea, api_enums::Connector::Fiuu => Self::Fiuu, diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 0650e5e6a4d..2675c337029 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -47,6 +47,10 @@ key1 = "key1" api_key = "access_key" key1 = "secret_key" +[facilitapay] +api_key = "password" +key1 = "username" # email id + [fiserv] api_key = "MyApiKey" key1 = "MerchantID" diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index fc3a777ee6e..959a7a90dba 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -353,6 +353,9 @@ pix = { country = "BR", currency = "BRL" } red_compra = { country = "CL", currency = "CLP" } red_pagos = { country = "UY", currency = "UYU" } +[pm_filters.facilitapay] +pix = { country = "BR", currency = "BRL" } + [pm_filters.globalpay] credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } @@ -404,7 +407,7 @@ gocardless = { long_lived_token = true, payment_method = "bank_debit" } billwerk = { long_lived_token = false, payment_method = "card" } [connector_customer] -connector_list = "gocardless,stax,stripe" +connector_list = "gocardless,stax,stripe,facilitapay" payout_connector_list = "nomupay,wise" [dummy_connector] @@ -529,4 +532,4 @@ paybox = { payment_method = "card" } redsys = { payment_method = "card" } [billing_connectors_payment_sync] -billing_connectors_which_require_payment_sync = "stripebilling, recurly" \ No newline at end of file +billing_connectors_which_require_payment_sync = "stripebilling, recurly"
2025-04-02T14:21:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR does the following: - Adds Facilitapay Connector configs - Enables Facilitapay Connector in Core - Feature Matrix - Pix Bank Transfer (QRCode flow) - Does not support `Manual` capture - AccessToken flow - Requires Connector Customer to be created prior to make a payment - Adds Cypress test coverage for Facilitapay Pix Bank transfer Also, this PR involves a small core change which is explained [here](https://github.com/juspay/hyperswitch/pull/7704#discussion_r2037127714). Quoted below: > Previously, `updated_customer` was called before constructing the `router_data`. `updated_customer` returns us the `connector_customer` in `payment_data` that then gets updated in the `router_data` while it gets constructed. > > Facilitapay requires us to pass `access_token` to create the `connectorCustomer` but `access_token` is available only in the `router_data`. This creates a cyclical dependency between `updated_customer` and `router_data`. > > To comes overcome this, we need to move `updated_customer` after `router_data`. > > `updated_customer` returns us the `connector_customer` value and it never gets updated in the `router_data` since it is called before calling `updated_customer` which results in `connector_customer_id` to go missing resulting in all payments that rely on `connector_customer_id` to fail. > > Hence, we need to update the `router_data` with `connector_customer` value that we get from `payment_data` returned by the `updated_customer` and the above lines does the same. ### 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). --> New connector integration. Closes #7732 ## 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>Authorize call</summary> ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_ptC2LQhN7u066v4fCKUcOEAWodGDoMl3We9YxN0cM4d7dal16ZSmt9EOdSJ0C6I4' \ --data-raw '{ "amount": 10400, "currency": "BRL", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 10400, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "browser_info": { "ip_address": "192.168.0.1", "user_agent": "MY LAPTOP RUNS ON m0z://a" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_HqjCP9OWtYlxg0KYwPMU", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "requires_payment_method", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_HqjCP9OWtYlxg0KYwPMU_secret_VZlpnxNdhvw9MExKApxo", "created": "2025-04-11T11:27:27.560Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T11:42:27.560Z", "fingerprint": null, "browser_info": { "ip_address": "192.168.0.1", "user_agent": "MY LAPTOP RUNS ON m0z://a" }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T11:27:27.583Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>Confirm call</summary> ```curl curl --location 'http://localhost:8080/payments/pay_HqjCP9OWtYlxg0KYwPMU/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_e765522f7c7543b9844fbcb1ab283a71' \ --data '{ "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": { "cpf": "866.656.235-80", "source_bank_account_id": "739d6b0a-e92a-40fd-9f58-6d4cdeb699bb", "destination_bank_account_id": "91f5cac1-9058-44b7-80e1-80c6f4a6f0bc", "pix_qr_expiry": "2025-04-11T19:53:54.807Z" } } }, "client_secret": "pay_HqjCP9OWtYlxg0KYwPMU_secret_VZlpnxNdhvw9MExKApxo" }' ``` ```json { "payment_id": "pay_HqjCP9OWtYlxg0KYwPMU", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "requires_customer_action", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 10400, "amount_received": null, "connector": "facilitapay", "client_secret": "pay_HqjCP9OWtYlxg0KYwPMU_secret_VZlpnxNdhvw9MExKApxo", "created": "2025-04-11T11:27:27.560Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": { "pix": { "pix_key": null, "cpf": "866.***.**5-80", "cnpj": null, "source_bank_account_id": "739d****-****-****-****-********99bb", "destination_bank_account_id": "91f5****-****-****-****-********f0bc" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "qr_code_information", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAegAAAHoCAAAAACnOyPQAAAUIklEQVR4Ae3gAZAkSZIkSRKLqpm7R0REZmZmVlVVVVV3d3d3d/fMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMdHd3d3dXV1VVVVVmZkZGRIS7m5kKz0xmV3d1d3dPz8zMzMxMYjVX/T9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLxb2NeNOIK85zEFeY5iRfOXCGuMFeI5888J3GFeU7ihTNXiOdknpO4wjx/4t/GvFBUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6DyIjIvGvH8iedkrjBXiCvMFeYK8ZzMFeI5medknpO5QlxhnpN4/sQV5gpxhblCXCGek7lCPH/iCvP8mReNeJFQuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKv5J4/szzJ56TuUI8J/OvY56TeP7MFeL5Ey+cuUI8f+b5E1eY50+8aMTzZ/5VqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5b+IeU7mCnGFeE7mOZnnT7xw4grz/JkrxBXmhTNXiH8d8ZzMFeIK85+KylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdU/ocx/zbmCnGFuUJcIV44c4W4wjx/4vkzV4h/HfNfgspV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVP6VzL+NuMJcIZ6TuUJcYV44cYW5QlxhrhDPyTx/4vkTz8k8f+IK8fyJK8wV4l/H/IegctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVF5H49zFXiCvMFeJfR1xhrhBXmCvEFeYK8ZzEFeaFM1eI5ySuMM/JXCGuMFeIF05cYZ6T+A9F5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLzH8tcIa4wV4jnzzwn85zMFeI5iefPPH/iOYl/HXGFuUK8cOIK85zMfwoqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/HyDzwokrzBXiRWOek3jhzBXi+TNXiBfOXCH+dcxzEs+feU7iCnOFuMJcIa4wz0k8J3OFeNGYfxUqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5F5gXjXnhzBXihTNXiH8b8fyZK8QLJ64wL5x44cQV5jmJ52SuEFeYK8RzMs9JXGFeJFSu+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/QOaFE1eYF048f+YKcYV5/sQV5vkTz8k8J/GczHMSz8lcIZ6Tef7EFeY5iedkrhDPyVwhrjAvnHhO5jmJK8yLhMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVP4F5jmJK8xzMs9JXCGuMFeIK8wV4grznMTzZ64Qz8k8f+IK85zEFeb5E1eYK8wV4grznMwV4gpzhXjRiCvMFeb5E/8mVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8i8Qz8lcIa4wV4jnZK4Qz594/sS/j7jCXGGuEM/JXCGuMFeIK8xzEleY509cYa4QL5x4TuYKcYW5QvyHoHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8BMi+ceOHMi0ZcYa4QV5grxHMyV4jnZJ6TeE7mCnGFeU7i+TNXiCvMFeL5M8+fuMJcIa4wL5x4/sxzEleYK8QV5oWictX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVf4G5QlxhrhDPSTwnc4V4TuIK85zMFeI5medPPCfznMxzEleYK8QV5vkTV5jnJJ6TuMI8f+YKcYW5Qjwnc4V4/sQV5gpxhXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v8AmRdOPH/mCvGczBXiCvP8iedkrhAvGnOFeE7mOYkrzBXiCvNvI54/8/yJK8y/jbjCPCdxhXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr/AXCGuMM/JPCfxnMQLZ64QV5jnT1xhrhBXmCvE82euEM+fuMJcIV405vkTz8k8J/H8mReN+DehctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wEyL5y4wjwncYV5/sQLZ144cYV5TuI5mSvEFeaFE1eY5088J3OFuMJcIZ6TuUJcYa4QV5jnTzwnc4V44cy/CpWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqLyIxPMnnj/znMRzEleYF424wjwn8fyJ589cIa4wz5+5QlxhnpN5TuIK85zMFeIK85zMFeIKcYW5QlxhrhDPSVxhXigqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/HyDzwokrzBXiOZkXTjx/5jmJK8wV4jmZ5ySuMC+ceNGY5ySuMFeIK8wV4grz/InnZJ6TuMJcIZ4/88KJK8wLReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKv8C88KJ589cYV44cYW5Qlxhnj/x/IkrzPNnrhAvnLjCXCGuMM/JXCGuMM/JvGjEFeZfR/yrULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v8AmRdOPCfz/IkrzBXiCvP8iRfOXCGeP/PCiSvMFeIK86IRz5+5Qjx/5grxnMwV4jmZK8QV5oUTz595oahc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/gMyLRjx/5jmJK8xzEi8ac4W4wjwncYW5QlxhnpN4TuYK8ZzM8yeuMC+cuMI8J3GFuUI8J/P8iSvMFeI5mSvEFeZFQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKi8i86IxV4grzBXmOYnnZP5tzBXiCnOFuUI8J/OvI64wL5y4wrxw5vkTV5grxBXmCvHvQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKi8icYW5QrxoxBXm+TNXiP9Y4jmJF848J3OFeE7iCnOFuUJcIZ6TuMJcIV448ZzE82euEFeYF4rKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B8i8cOIKc4V4/szzJ54/85zEczJXiOfPvGjEFeb5E8/JPH/i+TPPSVxhnpN44czzJ64wz5+4wrxQVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8i8wV4grzBXi+RNXmOdkXjjz/JkrxBXmOYkrzItGXGGek7lCPCdzhblCPH/i+RNXmOcknj9xhXlO4vkzLxIqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5F4jnz1whnpP59xFXmOdknpO4wlwhnpN5/szzJ1405grx/JnnZK4Qz8lcIZ6Tef7MvwuVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D5D51xH/Nub5E8/JvHDiP4d54cRzMleIF85cIa4wV4h/HXOFeE7mRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AnGFucJcIZ4/88KJF424wjx/5grx/JkrxHMyV4grzL+OuUJcYZ6TeP7MFeIK85zEFeb5E1eYK8S/CpWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqPw7meck/m3MFeI5iRfOXCFeOPOczHMSz8k8f+IK85zECyeuMM9JXGGek7jCPCfxb0Llqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/SuIK8/yZ5ySek3nhzAsnXjTiCnOFuMJcIZ6TuUI8J/GczHMSz8k8J/GcxL+OuML8u1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMqLSFxhnpO4wlwhnpN5TuIKc4W4wjx/4oUTz5+5Qlxh/nOY5ySeP/PCiSvMczJXiOdk/lWoXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f4DMfwxxhXlO4grznMQV5jmJK8wLJ54/8/yJK8wLJ64wz0lcYZ6TuMJcIa4wz5+4wlwhnpN5TuIK8/yJK8wLReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKv9G4gpzhblCvHDiOYkrzPMnrjBXiCvMFeIKc4W4wlwhrjBXiOdkXjTmCnGFucJcIZ6TuMJcIZ4/85zEFeYK8/yJK8yLhMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVP4F4jmZK8xzEleY5ySek3nRiCvMFeIK88KZK8QV5jmZK8TzZ56TeE7mCnGFeU7m+TPPSVxhnpN54cS/CZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PkPnXEVeY509cYZ6TeE7mCnGFuUI8J/OcxHMyV4grzItGPCdzhbjCvGjEFeYK8ZzMcxJXmOckrjDPn7jCXCGuMC8SKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Q+ReI52SuEFeYK8QV5vkzV4jnZK4QV5jnJJ4/c4W4wlwhrjBXiOfPXCGek7lCPH/mCvHCmRdOXGGek3j+zL8Llav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+o/CuJK8wV4gpzhbjCXCGuMP825gpxhblCXGGeP/GczItGPCdzhXhO5vkzV4jnzzwn8aIRV5h/EypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fIPOiES8ac4X4j2GuEFeY50+8aMwV4gpzhXj+zPMnrjDPn3hO5grxnMxzEleYK8RzMleI52ReKCpX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fUHkRmeckrjDPSTx/5gpxhblCvHDiCnOFeE7mCnOFeE7mOYnnJJ6TeeHEFeYK8ZzMczLPn7lCXGFeOPP8mRcJlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+QeeHEczLPSTwn85zEi8ZcIa4wV4grzAsnrjBXiH8d85zEFeYKcYW5QlxhnpN4Tub5E8+feU7iCvPvQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKv9G4vkTz5+5Qjwnc4V4TuI5iRfOvHDmCnGFuUJcIa4wV5grxBXmCvGcxHMyV4jnT1xhrhAvGvHCmReKylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wfIvGjEczIvGvGczHMSV5grxIvGXCGeP/OcxIvGXCFeOPP8iSvMcxJXmOdPPCdzhXhO5grxnMwLReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKi8i85zEFeY5iSvMFebfxlwhnj/x/JnnJF405jmZ5088J/HCiRdOPH/iOZkrxL8Jlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+o/BuZ5888J3GFuUI8J3OF+Lcxz0lcYZ6Tef7Ei0ZcYZ4/8/yZ5ySuMM/JPH/iCnGFeU7iRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AvFvY64wV4grzBXi+TNXiCvMcxLPSTwn88KJK8zzJ64wV4grzAsnrjBXiCvMFeI5iedPXGGek3lO4grzIqFy1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZUXkXnRiOckrjDPyVwhrjBXiCvMcxLPyVwhrjDPSTx/5vkTz0k8J/GczHMyV4grzHMyV4gXzrxozBXiCvNCUbnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr+SeP7MCyeuMM+feE7iCvOiEVeY50+8cOaFE1eYK8QV5jmZK8S/jvi3MS8SKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Q+W8inpP51xFXmOfPvHDiCnOFuMI8J/H8mSvEFeYK8fyZK8QV5grxnMwV4grz/IkrzIuEylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdU/puYF414TuaFE8/JPCfx/JkrxAsnrjDPSTx/5gpxhblCXGGeP3OFeE7m34TKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1T+lcy/jnlO4oUzV4grzPMnXjhzhXhO5grxnMQV5oUTz5+5QlxhrhDPSVxhnj/x/JkrxBXmX4XKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B8i8cOLfxlwhnpN5TuIK85zEczIvGnGFuUI8J/OcxBXmOYkrzBXiCvOiEVeYK8QV5t9GPH/mRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/A2Su+n+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wf8I0R1tG46Vec2AAAAAElFTkSuQmCC", "display_to_timestamp": 1744371750000, "qr_code_url": null, "display_text": null, "border_color": null }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "pix", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "aa3223d2-bd54-44d0-8816-fdbeae885c14", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "aa3223d2-bd54-44d0-8816-fdbeae885c14", "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_uEuYQIIpwmhh2zZgfnCK", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T11:42:27.560Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T11:27:32.090Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>QR Code</summary> <img width="691" alt="image" src="https://github.com/user-attachments/assets/5e088c40-aaea-4056-baf5-e81b1a88603d" /> <img width="704" alt="image" src="https://github.com/user-attachments/assets/b87e6a91-a4d7-4dfa-a846-1cf785e8b298" /> </details> <details> <summary>Retrieve Call</summary> ```curl curl --location 'http://localhost:8080/payments/pay_HqjCP9OWtYlxg0KYwPMU?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_ptC2LQhN7u066v4fCKUcOEAWodGDoMl3We9YxN0cM4d7dal16ZSmt9EOdSJ0C6I4' ``` ```json { "payment_id": "pay_HqjCP9OWtYlxg0KYwPMU", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "requires_customer_action", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 10400, "amount_received": null, "connector": "facilitapay", "client_secret": "pay_HqjCP9OWtYlxg0KYwPMU_secret_VZlpnxNdhvw9MExKApxo", "created": "2025-04-11T11:27:27.560Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": { "pix": { "pix_key": null, "cpf": "866.***.**5-80", "cnpj": null, "source_bank_account_id": "739d****-****-****-****-********99bb", "destination_bank_account_id": "91f5****-****-****-****-********f0bc" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "qr_code_information", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAegAAAHoCAAAAACnOyPQAAAUIklEQVR4Ae3gAZAkSZIkSRKLqpm7R0REZmZmVlVVVVV3d3d3d/fMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMdHd3d3dXV1VVVVVmZkZGRIS7m5kKz0xmV3d1d3dPz8zMzMxMYjVX/T9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLxb2NeNOIK85zEFeY5iRfOXCGuMFeI5888J3GFeU7ihTNXiOdknpO4wjx/4t/GvFBUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6DyIjIvGvH8iedkrjBXiCvMFeYK8ZzMFeI5medknpO5QlxhnpN4/sQV5gpxhblCXCGek7lCPH/iCvP8mReNeJFQuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKv5J4/szzJ56TuUI8J/OvY56TeP7MFeL5Ey+cuUI8f+b5E1eY50+8aMTzZ/5VqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5b+IeU7mCnGFeE7mOZnnT7xw4grz/JkrxBXmhTNXiH8d8ZzMFeIK85+KylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdU/ocx/zbmCnGFuUJcIV44c4W4wjx/4vkzV4h/HfNfgspV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVP6VzL+NuMJcIZ6TuUJcYV44cYW5QlxhrhDPyTx/4vkTz8k8f+IK8fyJK8wV4l/H/IegctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVF5H49zFXiCvMFeJfR1xhrhBXmCvEFeYK8ZzEFeaFM1eI5ySuMM/JXCGuMFeIF05cYZ6T+A9F5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLzH8tcIa4wV4jnzzwn85zMFeI5iefPPH/iOYl/HXGFuUK8cOIK85zMfwoqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/HyDzwokrzBXiRWOek3jhzBXi+TNXiBfOXCH+dcxzEs+feU7iCnOFuMJcIa4wz0k8J3OFeNGYfxUqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5F5gXjXnhzBXihTNXiH8b8fyZK8QLJ64wL5x44cQV5jmJ52SuEFeYK8RzMs9JXGFeJFSu+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/QOaFE1eYF048f+YKcYV5/sQV5vkTz8k8J/GczHMSz8lcIZ6Tef7EFeY5iedkrhDPyVwhrjAvnHhO5jmJK8yLhMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVP4F5jmJK8xzMs9JXCGuMFeIK8wV4grznMTzZ64Qz8k8f+IK85zEFeb5E1eYK8wV4grznMwV4gpzhXjRiCvMFeb5E/8mVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8i8Qz8lcIa4wV4jnZK4Qz594/sS/j7jCXGGuEM/JXCGuMFeIK8xzEleY509cYa4QL5x4TuYKcYW5QvyHoHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8BMi+ceOHMi0ZcYa4QV5grxHMyV4jnZJ6TeE7mCnGFeU7i+TNXiCvMFeL5M8+fuMJcIa4wL5x4/sxzEleYK8QV5oWictX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVf4G5QlxhrhDPSTwnc4V4TuIK85zMFeI5medPPCfznMxzEleYK8QV5vkTV5jnJJ6TuMI8f+YKcYW5Qjwnc4V4/sQV5gpxhXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v8AmRdOPH/mCvGczBXiCvP8iedkrhAvGnOFeE7mOYkrzBXiCvNvI54/8/yJK8y/jbjCPCdxhXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr/AXCGuMM/JPCfxnMQLZ64QV5jnT1xhrhBXmCvE82euEM+fuMJcIV405vkTz8k8J/H8mReN+DehctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wEyL5y4wjwncYV5/sQLZ144cYV5TuI5mSvEFeaFE1eY5088J3OFuMJcIZ6TuUJcYa4QV5jnTzwnc4V44cy/CpWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqLyIxPMnnj/znMRzEleYF424wjwn8fyJ589cIa4wz5+5QlxhnpN5TuIK85zMFeIK85zMFeIKcYW5QlxhrhDPSVxhXigqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/HyDzwokrzBXiOZkXTjx/5jmJK8wV4jmZ5ySuMC+ceNGY5ySuMFeIK8wV4grz/InnZJ6TuMJcIZ4/88KJK8wLReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKv8C88KJ589cYV44cYW5Qlxhnj/x/IkrzPNnrhAvnLjCXCGuMM/JXCGuMM/JvGjEFeZfR/yrULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v8AmRdOPCfz/IkrzBXiCvP8iRfOXCGeP/PCiSvMFeIK86IRz5+5Qjx/5grxnMwV4jmZK8QV5oUTz595oahc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/gMyLRjx/5jmJK8xzEi8ac4W4wjwncYW5QlxhnpN4TuYK8ZzM8yeuMC+cuMI8J3GFuUI8J/P8iSvMFeI5mSvEFeZFQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKi8i86IxV4grzBXmOYnnZP5tzBXiCnOFuUI8J/OvI64wL5y4wrxw5vkTV5grxBXmCvHvQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKi8icYW5QrxoxBXm+TNXiP9Y4jmJF848J3OFeE7iCnOFuUJcIZ6TuMJcIV448ZzE82euEFeYF4rKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B8i8cOIKc4V4/szzJ54/85zEczJXiOfPvGjEFeb5E8/JPH/i+TPPSVxhnpN44czzJ64wz5+4wrxQVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8i8wV4grzBXi+RNXmOdkXjjz/JkrxBXmOYkrzItGXGGek7lCPCdzhblCPH/i+RNXmOcknj9xhXlO4vkzLxIqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5F4jnz1whnpP59xFXmOdknpO4wlwhnpN5/szzJ1405grx/JnnZK4Qz8lcIZ6Tef7MvwuVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D5D51xH/Nub5E8/JvHDiP4d54cRzMleIF85cIa4wV4h/HXOFeE7mRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AnGFucJcIZ4/88KJF424wjx/5grx/JkrxHMyV4grzL+OuUJcYZ6TeP7MFeIK85zEFeb5E1eYK8S/CpWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqPw7meck/m3MFeI5iRfOXCFeOPOczHMSz8k8f+IK85zECyeuMM9JXGGek7jCPCfxb0Llqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/SuIK8/yZ5ySek3nhzAsnXjTiCnOFuMJcIZ6TuUI8J/GczHMSz8k8J/GcxL+OuML8u1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMqLSFxhnpO4wlwhnpN5TuIKc4W4wjx/4oUTz5+5Qlxh/nOY5ySeP/PCiSvMczJXiOdk/lWoXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f4DMfwxxhXlO4grznMQV5jmJK8wLJ54/8/yJK8wLJ64wz0lcYZ6TuMJcIa4wz5+4wlwhnpN5TuIK8/yJK8wLReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKv9G4gpzhblCvHDiOYkrzPMnrjBXiCvMFeIKc4W4wlwhrjBXiOdkXjTmCnGFucJcIZ6TuMJcIZ4/85zEFeYK8/yJK8yLhMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVP4F4jmZK8xzEleY5ySek3nRiCvMFeIK88KZK8QV5jmZK8TzZ56TeE7mCnGFeU7m+TPPSVxhnpN54cS/CZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PkPnXEVeY509cYZ6TeE7mCnGFuUI8J/OcxHMyV4grzItGPCdzhbjCvGjEFeYK8ZzMcxJXmOckrjDPn7jCXCGuMC8SKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Q+ReI52SuEFeYK8QV5vkzV4jnZK4QV5jnJJ4/c4W4wlwhrjBXiOfPXCGek7lCPH/mCvHCmRdOXGGek3j+zL8Llav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+o/CuJK8wV4gpzhbjCXCGuMP825gpxhblCXGGeP/GczItGPCdzhXhO5vkzV4jnzzwn8aIRV5h/EypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fIPOiES8ac4X4j2GuEFeY50+8aMwV4gpzhXj+zPMnrjDPn3hO5grxnMxzEleYK8RzMleI52ReKCpX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fUHkRmeckrjDPSTx/5gpxhblCvHDiCnOFeE7mCnOFeE7mOYnnJJ6TeeHEFeYK8ZzMczLPn7lCXGFeOPP8mRcJlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+QeeHEczLPSTwn85zEi8ZcIa4wV4grzAsnrjBXiH8d85zEFeYKcYW5QlxhnpN4Tub5E8+feU7iCvPvQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKv9G4vkTz5+5Qjwnc4V4TuI5iRfOvHDmCnGFuUJcIa4wV5grxBXmCvGcxHMyV4jnT1xhrhAvGvHCmReKylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wfIvGjEczIvGvGczHMSV5grxIvGXCGeP/OcxIvGXCFeOPP8iSvMcxJXmOdPPCdzhXhO5grxnMwLReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKi8i85zEFeY5iSvMFebfxlwhnj/x/JnnJF405jmZ5088J/HCiRdOPH/iOZkrxL8Jlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+o/BuZ5888J3GFuUI8J3OF+Lcxz0lcYZ6Tef7Ei0ZcYZ4/8/yZ5ySuMM/JPH/iCnGFeU7iRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AvFvY64wV4grzBXi+TNXiCvMcxLPSTwn88KJK8zzJ64wV4grzAsnrjBXiCvMFeI5iedPXGGek3lO4grzIqFy1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZUXkXnRiOckrjDPyVwhrjBXiCvMcxLPyVwhrjDPSTx/5vkTz0k8J/GczHMyV4grzHMyV4gXzrxozBXiCvNCUbnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr+SeP7MCyeuMM+feE7iCvOiEVeY50+8cOaFE1eYK8QV5jmZK8S/jvi3MS8SKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Q+W8inpP51xFXmOfPvHDiCnOFuMI8J/H8mSvEFeYK8fyZK8QV5grxnMwV4grz/IkrzIuEylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdU/puYF414TuaFE8/JPCfx/JkrxAsnrjDPSTx/5gpxhblCXGGeP3OFeE7m34TKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1T+lcy/jnlO4oUzV4grzPMnXjhzhXhO5grxnMQV5oUTz5+5QlxhrhDPSVxhnj/x/JkrxBXmX4XKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B8i8cOLfxlwhnpN5TuIK85zEczIvGnGFuUI8J/OcxBXmOYkrzBXiCvOiEVeYK8QV5t9GPH/mRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/A2Su+n+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wf8I0R1tG46Vec2AAAAAElFTkSuQmCC", "display_to_timestamp": 1744371750000, "qr_code_url": null, "display_text": null, "border_color": null }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "pix", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "aa3223d2-bd54-44d0-8816-fdbeae885c14", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "aa3223d2-bd54-44d0-8816-fdbeae885c14", "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_uEuYQIIpwmhh2zZgfnCK", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T11:42:27.560Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T12:02:17.950Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>Refund call</summary> ```curl curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ptC2LQhN7u066v4fCKUcOEAWodGDoMl3We9YxN0cM4d7dal16ZSmt9EOdSJ0C6I4' \ --data '{ "payment_id": "pay_HqjCP9OWtYlxg0KYwPMU", "amount": 600, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "error": { "type": "invalid_request", "message": "This Payment could not be refund because it has a status of requires_customer_action. The expected state is succeeded, partially_captured", "code": "IR_14" } } ``` </details> <details> <summary>Void call</summary> Authorize ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_ptC2LQhN7u066v4fCKUcOEAWodGDoMl3We9YxN0cM4d7dal16ZSmt9EOdSJ0C6I4' \ --data-raw '{ "amount": 10400, "currency": "BRL", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 10400, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "browser_info": { "ip_address": "192.168.0.1", "user_agent": "MY LAPTOP RUNS ON m0z://a" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_oEMHiZFEcOnYfhKdCGkX", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "requires_payment_method", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_oEMHiZFEcOnYfhKdCGkX_secret_4pCGB9AmNlBGvZUcT8La", "created": "2025-04-11T17:53:10.739Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T18:08:10.739Z", "fingerprint": null, "browser_info": { "ip_address": "192.168.0.1", "user_agent": "MY LAPTOP RUNS ON m0z://a" }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T17:53:10.747Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` Confirm ```curl curl --location 'http://localhost:8080/payments/pay_oEMHiZFEcOnYfhKdCGkX/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_e765522f7c7543b9844fbcb1ab283a71' \ --data '{ "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": { "cpf": "866.656.235-80", "source_bank_account_id": "739d6b0a-e92a-40fd-9f58-6d4cdeb699bb", "destination_bank_account_id": "91f5cac1-9058-44b7-80e1-80c6f4a6f0bc", "pix_qr_expiry": "2025-04-11T19:53:54.807Z" } } }, "client_secret": "pay_oEMHiZFEcOnYfhKdCGkX_secret_4pCGB9AmNlBGvZUcT8La" }' ``` ```json { "payment_id": "pay_oEMHiZFEcOnYfhKdCGkX", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "requires_customer_action", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 10400, "amount_received": null, "connector": "facilitapay", "client_secret": "pay_oEMHiZFEcOnYfhKdCGkX_secret_4pCGB9AmNlBGvZUcT8La", "created": "2025-04-11T17:53:10.739Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": { "pix": { "pix_key": null, "cpf": "866.***.**5-80", "cnpj": null, "source_bank_account_id": "739d****-****-****-****-********99bb", "destination_bank_account_id": "91f5****-****-****-****-********f0bc" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "qr_code_information", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAegAAAHoCAAAAACnOyPQAAAUO0lEQVR4Ae3gAZAkSZIkSRKLqpm7R0REZmZmVlVVVVV3d3d3d/fMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMdHd3d3dXV1VVVVVmZkZGRIS7m5kKz0xmV3d1d3dPz8zMzMxMYjVX/T9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLxb2OeP/GczHMSV5gXjbjCPH/iCvOcxBXmOYkrzHMSL5x5TuI5mSvEFeb5E/825oWictX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVF5F50YjnTzx/4vkTz5950YjnJK4wV5grxAsnrjBXiCvMFeL5M89JPCdxhXn+zItGvEioXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0DlX0k8f+b5E8+fuUK8aMwV4gpzhblCPCdzhbjCPCdxhXnhzBXiP4a5QrxoxPNn/lWoXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlv4i5QlwhrjBXiCvMFeIKc4W4wlwhrjAvGnGFeU7iCvOiMVeIK8wV4jmZ52SuEFeYK8QV5j8Vlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+o/BcRLxpxhblCPCfx/JkrxAsnXjhxhXn+xHMSV5grxBXiCvPCmf8SVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8q9k/m3MFeIKc4W4wjx/5l/HXCGek3n+xBXiOYnnZJ6TuMJcIf5zmP8QVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8iIS/zXEFeYKcYW5QlxhrhBXmCvEFeYK8ZzEFeY5mSvEFeYK8ZzEFeYKcYW5QlxhrhBXmOdPXGGek/gPReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DZP5ziRfOPH/iCnOFeOHM8yeuMM+feP7MFeJfx7xw4vkz/6moXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f4DMCyeuMFeIF4150YjnZJ4/8aIxV4h/HfPCiSvMCyeek3n+xBXmOYkXjflXoXLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8BlX8nc4W4wlwhrjBXiCvMFeIK88KJK8wLJ64QV5grxHMyz5+4wrxw4vkzz8k8f+IK85zEFeYK8ZzMcxJXmBcJlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+QedGIK8wV4jmZK8QV5vkT/z3MFeJFY64Qz5+5Qjwn88KJ5888J/GczHMSV5gXCZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqPwLxBXmOZkrxBXiCnOFuMJcIa4wV4gXzlwhrjDPSTwn8/yJF85cIa4wz8k8f+IKc4W4QlxhrhBXmOdknpO4wlxhrhDPSfybULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr/AXCGek3lO5gpxhblCPH/mCvGczBXiOYnnz1whrjDPn3jhzBXiRWOek3lO4oUTV5grzBXiCvOcxL8Llav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+Q+bcRz8k8J/GvY56TeP7MFeKFM89JXGGuEM/JXCGuMFeI52Sek7jCXCGuMFeIK8zzJ54/c4W4wjwn8ZzMC0Xlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AnGFuUK8cOI5meckrjBXiCvEFeY5mefPXCGek3nhxHMyL5y5Qjwn8ZzE82euEFeY589cIa4Qz0lcYZ6TeZFQuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKv5G5Qjwnc4V4TuKFMy+ceOHM8yeuMFeI5ySuMFeY5yReNOb5E1eY5ySuMFeIF848J3OFuMK8UFSu+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oPJvJJ4/cYV5TuYK8fyJK8y/jrlCvHDiCvPCiSvM8yeuMM+feE7mhRMvGvGczBXmRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AvOczBXiCvOczHMSV5grzBXiOZnnZJ4/c4V44cwV4jmJ58+8aMwV4oUzV4grzBXiCnOFeP7McxJXmCvEFeZFQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DZF404grznMQV5grx/JkrxBXmCnGFuUJcYa4QV5jnT1xhrhDPn3lO4grznMQV5jmJ52Sek7jC/NuI52ReOHGFeZFQuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/wCZF424wlwhrjDPn7jCXCFeOPP8iRfOXCGek7lCXGGuEM+feU7iCnOFuMJcIa4wz0lcYZ4/8ZzMcxLPyfyHoHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8BMi+cuMJcIa4wV4grzBXihTNXiOdknpN4TuY5iedkrhBXmCvEi8ZcIa4wV4grzPMnrjDPSTwn85zEczJXiCvMcxLPyVwhrjAvFJWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqLyIxPNnnpN5TuIK85zM8yeuMFeIK8QV5vkTV5grxBXm+RNXmOdkrhDPSVxhrhAvnHn+xHMyL5y4wlwh/k2oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f4DMi0Y8f+Y5iedkrhDPn3nhxHMy/zriCnOFuMJcIV4488KJ589cIZ4/85zEczLPn3hO5kVC5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLxohFXmOfPXCGuMM9JPH/mOYkrzHMSV5grxBXm+RPPyTwncYW4wjx/5gpxhblCXGGuEFeYF424wlwhrjBXiH8VKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9QeRGZK8RzEs9JvGjE82eek3hO5grxwpkrxL+OuMJcIZ6TuMJcIZ6TeOHEFeYK8cKJK8wV4grzr0Llqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AyovInGFeU7iCvP8iSvMFeIKc4V4TuIKc4V5TuIK88KJ52SeP/HCmSvEC2euEFeY589cIZ6Tef7EczLPSVxhXigqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1B5EZkrxBXm+RNXmOcknpN40YjnZJ6TuMK8aMQV5jmJK8wV4gpzhblCPH/iOYkrzBXmOZkrxHMSV5jnJJ4/8yKhctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVF5F4TuL5My+cuUL865jnzzwn8cKZ589cIa4wz0k8f+YKcYW5Qlwh/nXM82f+Xahc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/gMwLJ64wz0n825jnJJ6TedGI589cIf51zHMSz8k8f+Jfxzwn8aIxV4jnZF4kVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8m9knpO4wlwhnpN5TuIKc4V4TuIK85zEczIvnHlO4gpzhbhCXGGek7lCPCdzhXlO4jmZ5yReNOY5iSvMFeJfhcpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HyLxw4jmZ5yReNOYK8ZzMFeIK85zE82euEFeYK8R/DPP8iReNeU7iCnOFeP7MFeIKc4V4/syLhMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HyLxoxHMyz0lcYZ6TeE7mCnGFeU7iOZnnJK4wV4grzHMSz8lcIa4wV4jnZF404grznMQV5grx/JnnJK4wV4jnZP5dqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X+AzAsnnpN5TuKFM8+feE7mOYkXzjwncYV5/sQLZ56TeE7mCnGFuUJcYa4Qz595TuL5M1eIK8wV4jmZfxUqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5VxJXmCvMFeIKc4W4QlxhnpN50ZjnJJ6TeP7EczLPSVxhrhBXmCvMcxIvGvPCiedkrhDPyVwhnj9xhXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr/APCdxhbjCPCdxhXn+xBXmOYnnZJ6TuMJcIa4wL5x5TuIKc4W4wlwhnpN5TuYKcYW5Qjx/5grxnMwV4gpzhbjCXGGeP/GvQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DZF44cYV5/sRzMs9J/McwV4grzHMSz595/sQV5vkTz5+5Qlxh/m3EFebfRjwn80JRuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKv8BcIa4wz8k8J/GczPMnnpN54cTzJ64wV4grzAtnnj9xhblCXGGek7lCXGGek7jCXCGuMM+fuMI8f+I5mX8VKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Q+ReIF424wjwn8ZzMFeY5iSvMFeJfR1xhrhD/OuYK85zMcxIvGvOczItGPCdzhXlO4jmZF4rKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B8i8aMRzMleI589cIa4wV4h/G/PCiSvMcxLPn7lCXGGuEC+cef7EFeYK8fyZK8S/jrlCPCfzIqFy1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/ATL/OuL5M89JXGGuEM/JXCFeOPNvI64wz5+4wjx/4grz/IkrzPMnrjDPSTwn85zEczLPn7jCvEioXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0DlRSSek7lCPCfxwpl/G/H8mSvEFeYK88KZF848f+IKc4W4wlwhrjAvnLlCXGGuMP864grzQlG56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMq/QLxw5jmZ589cIa4wz8lcIZ6TuMJcIZ4/85zEczJXiCvMFeIK85zEFeYKcYW5QlxhnpO5Qlxhnj/x/IkrzBXi+TNXiBcJlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+QeeHEczJXiH8bc4W4wrxoxBXmOYkrzHMSz595TuI5meckrjBXiOfPvHDiCvOcxPNnrhBXmOckrjAvEipX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fIPOiEc/JvHDi+TPPSVxhrhAvnLlCvHDm+RPPn7lC/OuY5ySuMFeIK8wV4grznMRzMleIK8zzJ64wLxSVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D5D5txFXmOckXjTmCvH8mSvEv455TuJfx7xw4jmZK8QLZ54/8aIxV4jnz7xQVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8m9knj/znMRzMleIK8wV4grz/JnnTzx/4jmZ509cYV44cYW5QlwhrjDPn3hO4grznMzzJ64QV5jnJF4kVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8i8Q/zbmCvP8mSvEcxLPn7jCPCfznMQV5grxnMQV5jmJK8xzEleYF05cYa4QL5x4/sQV5jmZ5ySuMC8SKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9QeRGZF414TuIK8/yZK8RzMleI5ySuMM9JvGjM82eeP/P8medP/PuYF425QlxhXigqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5VxLPn/nXEc/JXCGek7lCvHDmCvH8iReNuMK8cOI5mSvMFeIKc4V44cS/jXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayn8x8fyJK8wV4grznMzzJ64wV4jnZK4Qz8lcIa4wz0k8J/PCiSvMczJXiCvMFeIKc4W4wrxw4grzIqFy1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZX/YuYKcYW5QlwhnpO4wlwhnpO5wjwnc4X41xHPyTwncYV5TuL5E8/JPCfznMzzJ64w/yZUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6Dyr2T+dcwV4jmZ589cIZ4/c4V4TuI5mefPPH/mCvH8iRfOvGjEFeaFE1eYK8wV4grzr0Llqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AyovIvFvI64wz0lcYa4wV4jnT1xhXjTiCvP8iSvMFeI5mefPPCfxnMwV4gpzhbjCXCGeP3OFuUI8f+IK8yKhctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wEyV/0/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8D/hEoC75kZ7w7cwAAAABJRU5ErkJggg==", "display_to_timestamp": 1744394897000, "qr_code_url": null, "display_text": null, "border_color": null }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "pix", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "33fe7dc7-25a0-4ba5-a7d2-4245fc0b2127", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "33fe7dc7-25a0-4ba5-a7d2-4245fc0b2127", "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_uEuYQIIpwmhh2zZgfnCK", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T18:08:10.739Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T17:53:19.350Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` Void ```curl curl --location 'http://localhost:8080/payments/pay_oEMHiZFEcOnYfhKdCGkX/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ptC2LQhN7u066v4fCKUcOEAWodGDoMl3We9YxN0cM4d7dal16ZSmt9EOdSJ0C6I4' \ --data '{"cancellation_reason":"requested_by_customer"}' ``` ```json { "payment_id": "pay_oEMHiZFEcOnYfhKdCGkX", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "cancelled", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 10400, "amount_received": null, "connector": "facilitapay", "client_secret": "pay_oEMHiZFEcOnYfhKdCGkX_secret_4pCGB9AmNlBGvZUcT8La", "created": "2025-04-11T17:53:10.739Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": { "pix": { "pix_key": null, "cpf": "866.***.**5-80", "cnpj": null, "source_bank_account_id": "739d****-****-****-****-********99bb", "destination_bank_account_id": "91f5****-****-****-****-********f0bc" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "qr_code_information", "image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAegAAAHoCAAAAACnOyPQAAAUO0lEQVR4Ae3gAZAkSZIkSRKLqpm7R0REZmZmVlVVVVV3d3d3d/fMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMdHd3d3dXV1VVVVVmZkZGRIS7m5kKz0xmV3d1d3dPz8zMzMxMYjVX/T9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLxb2OeP/GczHMSV5gXjbjCPH/iCvOcxBXmOYkrzHMSL5x5TuI5mSvEFeb5E/825oWictX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVF5F50YjnTzx/4vkTz5950YjnJK4wV5grxAsnrjBXiCvMFeL5M89JPCdxhXn+zItGvEioXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0DlX0k8f+b5E8+fuUK8aMwV4gpzhblCPCdzhbjCPCdxhXnhzBXiP4a5QrxoxPNn/lWoXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlv4i5QlwhrjBXiCvMFeIKc4W4wlwhrjAvGnGFeU7iCvOiMVeIK8wV4jmZ52SuEFeYK8QV5j8Vlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+o/BcRLxpxhblCPCfx/JkrxAsnXjhxhXn+xHMSV5grxBXiCvPCmf8SVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8q9k/m3MFeIKc4W4wjx/5l/HXCGek3n+xBXiOYnnZJ6TuMJcIf5zmP8QVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8iIS/zXEFeYKcYW5QlxhrhBXmCvEFeYK8ZzEFeY5mSvEFeYK8ZzEFeYKcYW5QlxhrhBXmOdPXGGek/gPReWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DZP5ziRfOPH/iCnOFeOHM8yeuMM+feP7MFeJfx7xw4vkz/6moXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f4DMCyeuMFeIF4150YjnZJ4/8aIxV4h/HfPCiSvMCyeek3n+xBXmOYkXjflXoXLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8BlX8nc4W4wlwhrjBXiCvMFeIK88KJK8wLJ64QV5grxHMyz5+4wrxw4vkzz8k8f+IK85zEFeYK8ZzMcxJXmBcJlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+QedGIK8wV4jmZK8QV5vkT/z3MFeJFY64Qz5+5Qjwn88KJ5888J/GczHMSV5gXCZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqPwLxBXmOZkrxBXiCnOFuMJcIa4wV4gXzlwhrjDPSTwn8/yJF85cIa4wz8k8f+IKc4W4QlxhrhBXmOdknpO4wlxhrhDPSfybULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr/AXCGek3lO5gpxhblCPH/mCvGczBXiOYnnz1whrjDPn3jhzBXiRWOek3lO4oUTV5grzBXiCvOcxL8Llav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+Q+bcRz8k8J/GvY56TeP7MFeKFM89JXGGuEM/JXCGuMFeI52Sek7jCXCGuMFeIK8zzJ54/c4W4wjwn8ZzMC0Xlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AnGFuUK8cOI5meckrjBXiCvEFeY5mefPXCGek3nhxHMyL5y5Qjwn8ZzE82euEFeY589cIa4Qz0lcYZ6TeZFQuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKv5G5Qjwnc4V4TuKFMy+ceOHM8yeuMFeI5ySuMFeY5yReNOb5E1eY5ySuMFeIF848J3OFuMK8UFSu+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oPJvJJ4/cYV5TuYK8fyJK8y/jrlCvHDiCvPCiSvM8yeuMM+feE7mhRMvGvGczBXmRULlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/Ayr/AvOczBXiCvOczHMSV5grzBXiOZnnZJ4/c4V44cwV4jmJ58+8aMwV4oUzV4grzBXiCnOFeP7McxJXmCvEFeZFQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DZF404grznMQV5grx/JkrxBXmCnGFuUJcYa4QV5jnT1xhrhDPn3lO4grznMQV5jmJ52Sek7jC/NuI52ReOHGFeZFQuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/wCZF424wlwhrjDPn7jCXCFeOPP8iRfOXCGek7lCXGGuEM+feU7iCnOFuMJcIa4wz0lcYZ4/8ZzMcxLPyfyHoHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8BMi+cuMJcIa4wV4grzBXihTNXiOdknpN4TuY5iedkrhBXmCvEi8ZcIa4wV4grzPMnrjDPSTwn85zEczJXiCvMcxLPyVwhrjAvFJWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqLyIxPNnnpN5TuIK85zM8yeuMFeIK8QV5vkTV5grxBXm+RNXmOdkrhDPSVxhrhAvnHn+xHMyL5y4wlwh/k2oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f4DMi0Y8f+Y5iedkrhDPn3nhxHMy/zriCnOFuMJcIV4488KJ589cIZ4/85zEczLPn3hO5kVC5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMq/wLxohFXmOfPXCGuMM9JPH/mOYkrzHMSV5grxBXm+RPPyTwncYW4wjx/5gpxhblCXGGuEFeYF424wlwhrjBXiH8VKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9QeRGZK8RzEs9JvGjE82eek3hO5grxwpkrxL+OuMJcIZ6TuMJcIZ6TeOHEFeYK8cKJK8wV4grzr0Llqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AyovInGFeU7iCvP8iSvMFeIKc4V4TuIKc4V5TuIK88KJ52SeP/HCmSvEC2euEFeY589cIZ6Tef7EczLPSVxhXigqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1B5EZkrxBXm+RNXmOcknpN40YjnZJ6TuMK8aMQV5jmJK8wV4gpzhblCPH/iOYkrzBXmOZkrxHMSV5jnJJ4/8yKhctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVF5F4TuL5My+cuUL865jnzzwn8cKZ589cIa4wz0k8f+YKcYW5Qlwh/nXM82f+Xahc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/gMwLJ64wz0n825jnJJ6TedGI589cIf51zHMSz8k8f+Jfxzwn8aIxV4jnZF4kVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8m9knpO4wlwhnpN5TuIKc4V4TuIK85zEczIvnHlO4gpzhbhCXGGek7lCPCdzhXlO4jmZ5yReNOY5iSvMFeJfhcpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HyLxw4jmZ5yReNOYK8ZzMFeIK85zE82euEFeYK8R/DPP8iReNeU7iCnOFeP7MFeIKc4V4/syLhMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HyLxoxHMyz0lcYZ6TeE7mCnGFeU7iOZnnJK4wV4grzHMSz8lcIa4wV4jnZF404grznMQV5grx/JnnJK4wV4jnZP5dqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X+AzAsnnpN5TuKFM8+feE7mOYkXzjwncYV5/sQLZ56TeE7mCnGFuUJcYa4Qz595TuL5M1eIK8wV4jmZfxUqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5VxJXmCvMFeIKc4W4QlxhnpN50ZjnJJ6TeP7EczLPSVxhrhBXmCvMcxIvGvPCiedkrhDPyVwhnj9xhXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayr/APCdxhbjCPCdxhXn+xBXmOYnnZJ6TuMJcIa4wL5x5TuIKc4W4wlwhnpN5TuYKcYW5Qjx/5grxnMwV4gpzhbjCXGGeP/GvQuWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DZF44cYV5/sRzMs9J/McwV4grzHMSz595/sQV5vkTz5+5Qlxh/m3EFebfRjwn80JRuer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKv8BcIa4wz8k8J/GczPMnnpN54cTzJ64wV4grzAtnnj9xhblCXGGek7lCXGGek7jCXCGuMM+fuMI8f+I5mX8VKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Q+ReIF424wjwn8ZzMFeY5iSvMFeJfR1xhrhD/OuYK85zMcxIvGvOczItGPCdzhXlO4jmZF4rKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B8i8aMRzMleI589cIa4wV4h/G/PCiSvMcxLPn7lCXGGuEC+cef7EFeYK8fyZK8S/jrlCPCfzIqFy1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/ATL/OuL5M89JXGGuEM/JXCFeOPNvI64wz5+4wjx/4grz/IkrzPMnrjDPSTwn85zEczLPn7jCvEioXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0DlRSSek7lCPCfxwpl/G/H8mSvEFeYK88KZF848f+IKc4W4wlwhrjAvnLlCXGGuMP864grzQlG56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMq/QLxw5jmZ589cIa4wz8lcIZ6TuMJcIZ4/85zEczJXiCvMFeIK85zEFeYKcYW5QlxhnpO5Qlxhnj/x/IkrzBXi+TNXiBcJlav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+QeeHEczJXiH8bc4W4wrxoxBXmOYkrzHMSz595TuI5meckrjBXiOfPvHDiCvOcxPNnrhBXmOckrjAvEipX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fIPOiEc/JvHDi+TPPSVxhrhAvnLlCvHDm+RPPn7lC/OuY5ySuMFeIK8wV4grznMRzMleIK8zzJ64wLxSVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D5D5txFXmOckXjTmCvH8mSvEv455TuJfx7xw4jmZK8QLZ54/8aIxV4jnz7xQVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8m9knj/znMRzMleIK8wV4grz/JnnTzx/4jmZ509cYV44cYW5QlwhrjDPn3hO4grznMzzJ64QV5jnJF4kVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+g8i8Q/zbmCvP8mSvEcxLPn7jCPCfznMQV5grxnMQV5jmJK8xzEleYF05cYa4QL5x4/sQV5jmZ5ySuMC8SKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9QeRGZF414TuIK8/yZK8RzMleI5ySuMM9JvGjM82eeP/P8medP/PuYF425QlxhXigqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1D5VxLPn/nXEc/JXCGek7lCvHDmCvH8iReNuMK8cOI5mSvMFeIKc4V44cS/jXmRULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+Ayn8x8fyJK8wV4grznMzzJ64wV4jnZK4Qz8lcIa4wz0k8J/PCiSvMczJXiCvMFeIKc4W4wrxw4grzIqFy1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZX/YuYKcYW5QlwhnpO4wlwhnpO5wjwnc4X41xHPyTwncYV5TuL5E8/JPCfznMzzJ64w/yZUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6Dyr2T+dcwV4jmZ589cIZ4/c4V4TuI5mefPPH/mCvH8iRfOvGjEFeaFE1eYK8wV4grzr0Llqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AyovIvFvI64wz0lcYa4wV4jnT1xhXjTiCvP8iSvMFeI5mefPPCfxnMwV4gpzhbjCXCGeP3OFuUI8f+IK8yKhctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wEyV/0/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8DKlf9f0Dlqv8PqFz1/wGVq/4/oHLV/wdUrvr/gMpV/x9Quer/AypX/X9A5ar/D6hc9f8Blav+P6By1f8HVK76/4DKVf8fULnq/wMqV/1/QOWq/w+oXPX/AZWr/j+gctX/B1Su+v+AylX/H1C56v8D/hEoC75kZ7w7cwAAAABJRU5ErkJggg==", "display_to_timestamp": 1744394897000, "qr_code_url": null, "display_text": null, "border_color": null }, "cancellation_reason": "requested_by_customer", "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "pix", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "33fe7dc7-25a0-4ba5-a7d2-4245fc0b2127", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "33fe7dc7-25a0-4ba5-a7d2-4245fc0b2127", "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_uEuYQIIpwmhh2zZgfnCK", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T18:08:10.739Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T17:53:20.936Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>Manual Capture</summary> Authorize ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_ptC2LQhN7u066v4fCKUcOEAWodGDoMl3We9YxN0cM4d7dal16ZSmt9EOdSJ0C6I4' \ --data-raw '{ "amount": 10400, "currency": "BRL", "confirm": false, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 10400, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "browser_info": { "ip_address": "192.168.0.1", "user_agent": "MY LAPTOP RUNS ON m0z://a" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_ytZ1ZAAsTwKK0F7uA2IH", "merchant_id": "postman_merchant_GHAction_1744364064", "status": "requires_payment_method", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_ytZ1ZAAsTwKK0F7uA2IH_secret_HjrEsQIrDAQunFZVLQY4", "created": "2025-04-11T17:55:46.411Z", "currency": "BRL", "customer_id": null, "customer": { "id": null, "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_d88fTeKAHe2MonTWe8Dk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-11T18:10:46.411Z", "fingerprint": null, "browser_info": { "ip_address": "192.168.0.1", "user_agent": "MY LAPTOP RUNS ON m0z://a" }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-11T17:55:46.418Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` Confirm ```curl curl --location 'http://localhost:8080/payments/pay_ytZ1ZAAsTwKK0F7uA2IH/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_e765522f7c7543b9844fbcb1ab283a71' \ --data '{ "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": { "cpf": "866.656.235-80", "source_bank_account_id": "739d6b0a-e92a-40fd-9f58-6d4cdeb699bb", "destination_bank_account_id": "91f5cac1-9058-44b7-80e1-80c6f4a6f0bc", "pix_qr_expiry": "2025-04-11T19:53:54.807Z" } } }, "client_secret": "pay_ytZ1ZAAsTwKK0F7uA2IH_secret_HjrEsQIrDAQunFZVLQY4" }' ``` ```json { "error": { "type": "invalid_request", "message": "Payment method type not supported", "code": "IR_19", "reason": "manual is not supported by facilitapay" } } ``` </details> <details> <summary>Cypress tests</summary> <img width="889" alt="image" src="https://github.com/user-attachments/assets/09dd0c44-5ca4-4387-bcd4-0555bdc6a615" /> </details> ## 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` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
v1.113.0
776bde00efce8be35e0c63c1bdc6215921babddf
776bde00efce8be35e0c63c1bdc6215921babddf
juspay/hyperswitch
juspay__hyperswitch-7710
Bug: [Nexixpay]: handle error_code and error_message in failure responses of nexixpay Nexixpay does not send error_code and error_message in case of failure responses. We will send NO_ERROR_CODE and nexixpay operation result as error_message in this case.
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs index 68f3b4bb695..32e630a2be7 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs @@ -8,7 +8,7 @@ use common_utils::{ use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, - router_data::{ConnectorAuthType, RouterData}, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ refunds::{Execute, RSync}, SetupMandate, @@ -25,9 +25,10 @@ use hyperswitch_domain_models::{ PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, RefundsRouterData, }, }; -use hyperswitch_interfaces::errors; +use hyperswitch_interfaces::{consts::NO_ERROR_CODE, errors}; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; +use strum::Display; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, @@ -305,6 +306,23 @@ fn update_nexi_meta_data( })) } +pub fn get_error_response( + operation_result: NexixpayPaymentStatus, + status_code: u16, +) -> ErrorResponse { + ErrorResponse { + status_code, + code: NO_ERROR_CODE.to_string(), + message: operation_result.to_string(), + reason: Some(operation_result.to_string()), + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeDSAuthData { @@ -425,22 +443,35 @@ impl<F> is_auto_capture, })?); - Ok(Self { - status: AttemptStatus::from(item.response.operation.operation_result), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId( - item.response.operation.order_id.clone(), - ), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata, - network_txn_id: None, - connector_response_reference_id: Some(item.response.operation.order_id), - incremental_authorization_allowed: None, - charges: None, + let status = AttemptStatus::from(item.response.operation.operation_result.clone()); + match status { + AttemptStatus::Failure => { + let response = Err(get_error_response( + item.response.operation.operation_result.clone(), + item.http_code, + )); + Ok(Self { + response, + ..item.data + }) + } + _ => Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.operation.order_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata, + network_txn_id: None, + connector_response_reference_id: Some(item.response.operation.order_id), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data }), - ..item.data - }) + } } } @@ -632,7 +663,7 @@ impl TryFrom<&ConnectorAuthType> for NexixpayAuthType { } } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Display, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum NexixpayPaymentStatus { Authorized, @@ -821,51 +852,80 @@ impl<F> }, psync_flow: NexixpayPaymentIntent::Authorize })); - Ok(Self { - status: AttemptStatus::from(response_body.operation.operation_result.clone()), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId( - response_body.operation.order_id.clone(), - ), - redirection_data: Box::new(Some(redirection_form.clone())), - mandate_reference: Box::new(Some(MandateReference { - connector_mandate_id: item - .data - .connector_mandate_request_reference_id - .clone(), - payment_method_id: None, - mandate_metadata: None, - connector_mandate_request_reference_id: None, - })), - connector_metadata, - network_txn_id: None, - connector_response_reference_id: Some( - response_body.operation.order_id.clone(), - ), - incremental_authorization_allowed: None, - charges: None, + let status = AttemptStatus::from(response_body.operation.operation_result.clone()); + match status { + AttemptStatus::Failure => { + let response = Err(get_error_response( + response_body.operation.operation_result.clone(), + item.http_code, + )); + Ok(Self { + response, + ..item.data + }) + } + _ => Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + response_body.operation.order_id.clone(), + ), + redirection_data: Box::new(Some(redirection_form.clone())), + mandate_reference: Box::new(Some(MandateReference { + connector_mandate_id: item + .data + .connector_mandate_request_reference_id + .clone(), + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + })), + connector_metadata, + network_txn_id: None, + connector_response_reference_id: Some( + response_body.operation.order_id.clone(), + ), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data }), - ..item.data - }) + } + } + NexixpayPaymentsResponse::MandateResponse(ref mandate_response) => { + let status = + AttemptStatus::from(mandate_response.operation.operation_result.clone()); + match status { + AttemptStatus::Failure => { + let response = Err(get_error_response( + mandate_response.operation.operation_result.clone(), + item.http_code, + )); + Ok(Self { + response, + ..item.data + }) + } + _ => Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + mandate_response.operation.order_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + mandate_response.operation.order_id.clone(), + ), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }), + } } - NexixpayPaymentsResponse::MandateResponse(ref mandate_response) => Ok(Self { - status: AttemptStatus::from(mandate_response.operation.operation_result.clone()), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId( - mandate_response.operation.order_id.clone(), - ), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: Some( - mandate_response.operation.order_id.clone(), - ), - incremental_authorization_allowed: None, - charges: None, - }), - ..item.data - }), } } } @@ -975,27 +1035,42 @@ impl<F> } else { AttemptStatus::from(item.response.operation.operation_result.clone()) }; - Ok(Self { - status, - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId( - item.response.operation.order_id.clone(), - ), - redirection_data: Box::new(None), - mandate_reference: Box::new(Some(MandateReference { - connector_mandate_id: item.data.connector_mandate_request_reference_id.clone(), - payment_method_id: None, - mandate_metadata: None, - connector_mandate_request_reference_id: None, - })), - connector_metadata, - network_txn_id: None, - connector_response_reference_id: Some(item.response.operation.order_id), - incremental_authorization_allowed: None, - charges: None, + match status { + AttemptStatus::Failure => { + let response = Err(get_error_response( + item.response.operation.operation_result.clone(), + item.http_code, + )); + Ok(Self { + response, + ..item.data + }) + } + _ => Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.operation.order_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(Some(MandateReference { + connector_mandate_id: item + .data + .connector_mandate_request_reference_id + .clone(), + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + })), + connector_metadata, + network_txn_id: None, + connector_response_reference_id: Some(item.response.operation.order_id), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data }), - ..item.data - }) + } } } @@ -1122,25 +1197,32 @@ impl TryFrom<&NexixpayRouterData<&PaymentsCompleteAuthorizeRouterData>> .into()) } }; - let contract_id = Secret::new( - item.router_data - .connector_mandate_request_reference_id - .clone() - .ok_or_else(|| errors::ConnectorError::MissingRequiredField { - field_name: "connector_mandate_request_reference_id", - })?, - ); + + let recurrence_request_obj = if item.router_data.request.is_mandate_payment() { + let contract_id = Secret::new( + item.router_data + .connector_mandate_request_reference_id + .clone() + .ok_or_else(|| errors::ConnectorError::MissingRequiredField { + field_name: "connector_mandate_request_reference_id", + })?, + ); + Some(RecurrenceRequest { + action: NexixpayRecurringAction::ContractCreation, + contract_id, + contract_type: ContractType::MitUnscheduled, + }) + } else { + None + }; + Ok(Self { order: order_data, card: card?, operation_id, capture_type, three_d_s_auth_data, - recurrence: Some(RecurrenceRequest { - action: NexixpayRecurringAction::ContractCreation, - contract_id, - contract_type: ContractType::MitUnscheduled, - }), + recurrence: recurrence_request_obj, }) } } @@ -1159,25 +1241,41 @@ impl<F> PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - Ok(Self { - status: AttemptStatus::from(item.response.operation_result), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), - redirection_data: Box::new(None), - mandate_reference: Box::new(Some(MandateReference { - connector_mandate_id: item.data.connector_mandate_request_reference_id.clone(), - payment_method_id: None, - mandate_metadata: None, - connector_mandate_request_reference_id: None, - })), - connector_metadata: item.data.request.connector_meta.clone(), - network_txn_id: None, - connector_response_reference_id: Some(item.response.order_id.clone()), - incremental_authorization_allowed: None, - charges: None, + let status = AttemptStatus::from(item.response.operation_result.clone()); + match status { + AttemptStatus::Failure => { + let response = Err(get_error_response( + item.response.operation_result.clone(), + item.http_code, + )); + Ok(Self { + response, + ..item.data + }) + } + _ => Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), + redirection_data: Box::new(None), + mandate_reference: Box::new(Some(MandateReference { + connector_mandate_id: item + .data + .connector_mandate_request_reference_id + .clone(), + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + })), + connector_metadata: item.data.request.connector_meta.clone(), + network_txn_id: None, + connector_response_reference_id: Some(item.response.order_id.clone()), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data }), - ..item.data - }) + } } } @@ -1349,26 +1447,43 @@ impl }, psync_flow: NexixpayPaymentIntent::Authorize })); - Ok(Self { - status: AttemptStatus::from(item.response.operation.operation_result.clone()), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId( - item.response.operation.order_id.clone(), - ), - redirection_data: Box::new(Some(redirection_form.clone())), - mandate_reference: Box::new(Some(MandateReference { - connector_mandate_id: item.data.connector_mandate_request_reference_id.clone(), - payment_method_id: None, - mandate_metadata: None, - connector_mandate_request_reference_id: None, - })), - connector_metadata, - network_txn_id: None, - connector_response_reference_id: Some(item.response.operation.order_id.clone()), - incremental_authorization_allowed: None, - charges: None, + + let status = AttemptStatus::from(item.response.operation.operation_result.clone()); + match status { + AttemptStatus::Failure => { + let response = Err(get_error_response( + item.response.operation.operation_result.clone(), + item.http_code, + )); + Ok(Self { + response, + ..item.data + }) + } + _ => Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.operation.order_id.clone(), + ), + redirection_data: Box::new(Some(redirection_form.clone())), + mandate_reference: Box::new(Some(MandateReference { + connector_mandate_id: item + .data + .connector_mandate_request_reference_id + .clone(), + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + })), + connector_metadata, + network_txn_id: None, + connector_response_reference_id: Some(item.response.operation.order_id.clone()), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data }), - ..item.data - }) + } } }
2025-04-03T07:43:12Z
## 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 --> Nexixpay does not send error_code and error_message in case of failure responses. We will store NO_ERROR_CODE and nexixpay operation result as error_message in this case in our DB. This is sent in outgoing webhooks to the merchants. Possible values of error messages: 1. Declined 2. DeniedByRisk 3. ThreedsFailed 4. Failed ### 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). --> Currently error_code and error_message goes null in case of webhooks to merchants for nexixpay. We need to pass NO_ERROR_CODE and nexixpay operation result as error_message as connector doesn't sends us any message or code. ## 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 to test: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nRAnqXGtbt60CdOO7rfovzh4MdEAIiaqnWc78AdQIx4yWnDXIKetpkjGFOvwFPcb' \ --data-raw '{ "amount": 3596, "currency": "EUR", "amount_to_capture": 3596, "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4742158750987704", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "861" } }, "confirm": true, "profile_id": "pro_PBNVTjuDfM7y2MyljTkG", "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "setup_future_usage": "off_session", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "description": "Its my first payment request", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IT", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IT", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 3545, "account_name": "transaction_processing" } ], "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" }, "customer_acceptance": { "acceptance_type": "online", "accepted_at":"1963-05-03T04:07:52.723Z", "online": { "ip_address":"127.0.0.1", "user_agent": "amet irure esse" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal", "request_incremental_authorization": false, "merchant_order_reference_id": "test_ord", "session_expiry": 900 }' ``` Webhook for failed payment via nexixpay: ``` { "merchant_id": "merchant_1743678217", "event_id": "evt_0195fbf468957b539666947e6762e0af", "event_type": "payment_failed", "content": { "type": "payment_details", "object": { "payment_id": "pay_LOrSTDvs2fs1rntR8Bv7", "merchant_id": "merchant_1743678217", "status": "failed", "amount": 3596, "net_amount": 3596, "shipping_cost": null, "amount_capturable": 3596, "amount_received": null, "connector": "nexixpay", "client_secret": "pay_LOrSTDvs2fs1rntR8Bv7_secret_ZAC52wYDhKokuUvZjKws", "created": "2025-04-03T14:00:35.887Z", "currency": "EUR", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "[email protected]", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "7704", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "474215", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_r5dkurdxxncdiAxecZp2", "shipping": { "address": { "city": "San Fransico", "country": "IT", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "billing": { "address": { "city": "San Fransico", "country": "IT", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 3545, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": "John Doe", "phone": "9999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": "No error code", "error_message": "ThreedsFailed", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": true, "connector_transaction_id": "pay_LOrSTDvs2fs1rntR8Bv7_1", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" }, "braintree": null }, "feature_metadata": null, "reference_id": "pay_LOrSTDvs2fs1rntR8Bv7_1", "payment_link": null, "profile_id": "pro_9rN5ntPWxQFSDMxRHEZ5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_bB3eKYzBDOgKte0bcmKl", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-03T14:15:35.887Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_stzSPzwuoRaFMpPpYb9r", "payment_method_status": "inactive", "updated": "2025-04-03T14:00:53.638Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "test_ord", "order_tax_amount": null, "connector_mandate_id": "6Hj8lx8blnGI3EMXRX", "card_discovery": "manual", "issuer_error_code": null, "issuer_error_message": null } }, "timestamp": "2025-04-03T14:00:53.654Z" } ``` ## 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.113.0
bd32dd4f0f259336f004a2358a7771652a3c6689
bd32dd4f0f259336f004a2358a7771652a3c6689
juspay/hyperswitch
juspay__hyperswitch-7723
Bug: Add invoice number and email in AuthorizeDotNet connector Add invoice number and email in AuthorizeDotNet connector
diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index bb93d9279de..9bd809c124f 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -5,6 +5,7 @@ use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::{Encode, OptionExt, ValueExt}, + pii::Email, request::Method, }; use error_stack::ResultExt; @@ -36,6 +37,12 @@ use crate::{ }, }; +const MAX_ID_LENGTH: usize = 20; + +fn get_random_string() -> String { + Alphanumeric.sample_string(&mut rand::thread_rng(), MAX_ID_LENGTH) +} + #[derive(Debug, Serialize)] pub enum TransactionType { #[serde(rename = "authCaptureTransaction")] @@ -207,6 +214,7 @@ struct PaymentProfileDetails { #[serde(rename_all = "camelCase")] pub struct CustomerDetails { id: String, + email: Option<Email>, } #[derive(Debug, Serialize)] @@ -230,6 +238,7 @@ pub struct BillTo { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Order { + invoice_number: String, description: String, } @@ -611,7 +620,7 @@ impl TryFrom<&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>> let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?; - let ref_id = if item.router_data.connector_request_reference_id.len() <= 20 { + let ref_id = if item.router_data.connector_request_reference_id.len() <= MAX_ID_LENGTH { Some(item.router_data.connector_request_reference_id.clone()) } else { None @@ -727,9 +736,17 @@ impl }), profile: None, order: Order { + invoice_number: get_random_string(), description: item.router_data.connector_request_reference_id.clone(), }, - customer: None, + customer: Some(CustomerDetails { + id: if item.router_data.payment_id.len() <= MAX_ID_LENGTH { + item.router_data.payment_id.clone() + } else { + get_random_string() + }, + email: item.router_data.request.get_optional_email(), + }), bill_to: item .router_data .get_optional_billing() @@ -798,9 +815,17 @@ impl }) }), order: Order { + invoice_number: get_random_string(), description: item.router_data.connector_request_reference_id.clone(), }, - customer: None, + customer: Some(CustomerDetails { + id: if item.router_data.payment_id.len() <= MAX_ID_LENGTH { + item.router_data.payment_id.clone() + } else { + get_random_string() + }, + email: item.router_data.request.get_optional_email(), + }), bill_to: None, user_fields: match item.router_data.request.metadata.clone() { Some(metadata) => Some(UserFields { @@ -835,24 +860,21 @@ impl &Card, ), ) -> Result<Self, Self::Error> { - let (profile, customer) = if item.router_data.request.is_mandate_payment() { - ( - Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { - create_profile: true, - })), - Some(CustomerDetails { - //The payment ID is included in the customer details because the connector requires unique customer information with a length of fewer than 20 characters when creating a mandate. - //If the length exceeds 20 characters, a random alphanumeric string is used instead. - id: if item.router_data.payment_id.len() <= 20 { - item.router_data.payment_id.clone() - } else { - Alphanumeric.sample_string(&mut rand::thread_rng(), 20) - }, - }), - ) - } else { - (None, None) - }; + let (profile, customer) = ( + Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { + create_profile: true, + })), + Some(CustomerDetails { + //The payment ID is included in the customer details because the connector requires unique customer information with a length of fewer than 20 characters when creating a mandate. + //If the length exceeds 20 characters, a random alphanumeric string is used instead. + id: if item.router_data.payment_id.len() <= MAX_ID_LENGTH { + item.router_data.payment_id.clone() + } else { + get_random_string() + }, + email: item.router_data.request.get_optional_email(), + }), + ); Ok(Self { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, @@ -864,6 +886,7 @@ impl })), profile, order: Order { + invoice_number: get_random_string(), description: item.router_data.connector_request_reference_id.clone(), }, customer, @@ -911,23 +934,19 @@ impl &WalletData, ), ) -> Result<Self, Self::Error> { - let (profile, customer) = if item.router_data.request.is_mandate_payment() { - ( - Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { - create_profile: true, - })), - Some(CustomerDetails { - id: if item.router_data.payment_id.len() <= 20 { - item.router_data.payment_id.clone() - } else { - Alphanumeric.sample_string(&mut rand::thread_rng(), 20) - }, - }), - ) - } else { - (None, None) - }; - + let (profile, customer) = ( + Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { + create_profile: true, + })), + Some(CustomerDetails { + id: if item.router_data.payment_id.len() <= MAX_ID_LENGTH { + item.router_data.payment_id.clone() + } else { + get_random_string() + }, + email: item.router_data.request.get_optional_email(), + }), + ); Ok(Self { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, @@ -938,6 +957,7 @@ impl )?), profile, order: Order { + invoice_number: get_random_string(), description: item.router_data.connector_request_reference_id.clone(), }, customer,
2025-04-04T13:24:23Z
## 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/7723) ## Description <!-- Describe your changes in detail --> Added invoice number and email in AuthorizeDotNet 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). --> This feature is a merchant ask. They need it to claim chargebacks. ## 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 Tests 1. Connector Create - AuthorizeDotNet Request: ``` curl --location 'http://localhost:8080/account/merchant_1744026981/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Y3QfvvJdv4BhlHCTUDfWpwTPLyZnFw3nSkJ3pDAOL1ZJvW7foEdck5LuqNh5N1Nj' \ --data '{ "connector_type": "payment_processor", "connector_name": "authorizedotnet", "connector_account_details": { "auth_type": "BodyKey", "api_key": "API KEY", "key1": "KEY1" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default", }' ``` Response: ``` { "connector_type": "payment_processor", "connector_name": "authorizedotnet", "connector_label": "authorizedotnet_US_default", "merchant_connector_id": "mca_z9HhKBpL6GKf6kLyTqzO", "profile_id": "pro_APc2BIFDjU2pAlUnqbD0", "connector_account_details": { "auth_type": "BodyKey", "api_key": "29*****G3", "key1": "34************nv" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret", "additional_secret": null }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, } ``` 2. Payments - Create Request: ``` { "amount": 35308, "currency": "USD", "confirm": false, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country":"US", "first_name": "PiX" } } } ``` Response: ``` { "payment_id": "pay_AhwRHSRSeXE0HUgmIDh4", "merchant_id": "merchant_1744026981", "status": "requires_payment_method", "amount": 35308, "net_amount": 35308, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_AhwRHSRSeXE0HUgmIDh4_secret_rlGIHoYt8wloO4iCKQmq", "created": "2025-04-07T11:56:35.755Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1744026995, "expires": 1744030595, "secret": "epk_0d1d33b9a9964dd08fda3c8894ea808a" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_APc2BIFDjU2pAlUnqbD0", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-07T12:11:35.755Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-07T11:56:35.794Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "issuer_error_code": null, "issuer_error_message": null } ``` 3. Payments - Confirm Request: ``` { "connector": ["authorizedotnet"], "capture_method": "automatic", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "370000000000002", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } ``` Response: ``` { "payment_id": "pay_AhwRHSRSeXE0HUgmIDh4", "merchant_id": "merchant_1744026981", "status": "succeeded", "amount": 35308, "net_amount": 35308, "shipping_cost": null, "amount_capturable": 0, "amount_received": 35308, "connector": "authorizedotnet", "client_secret": "pay_AhwRHSRSeXE0HUgmIDh4_secret_rlGIHoYt8wloO4iCKQmq", "created": "2025-04-07T11:56:35.755Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0002", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "370000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "120060815605", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "120060815605", "payment_link": null, "profile_id": "pro_APc2BIFDjU2pAlUnqbD0", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_z9HhKBpL6GKf6kLyTqzO", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-07T12:11:35.755Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-07T11:56:41.667Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "issuer_error_code": null, "issuer_error_message": null } ``` Screenshot of the AuthorizeDotNet Sandbox dashboard: <img width="1286" alt="Screenshot 2025-04-04 at 6 56 52 PM" src="https://github.com/user-attachments/assets/2ca2bc0f-4f01-4aac-b97b-cdecc57646c6" /> ## 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.113.0
e88672c97cc02001fb656e550cd670eda424d9c9
e88672c97cc02001fb656e550cd670eda424d9c9
juspay/hyperswitch
juspay__hyperswitch-7699
Bug: web-docker pull from docker hub
diff --git a/docker-compose.yml b/docker-compose.yml index ea1ebb3dd12..cb39b23b133 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -149,15 +149,14 @@ services: ### Web Client hyperswitch-web: + image: docker.juspay.io/juspaydotin/hyperswitch-web:latest + pull_policy: always ports: - "9050:9050" - "9060:9060" - "5252:5252" networks: - router_net - build: - context: ./docker - dockerfile: web.Dockerfile depends_on: hyperswitch-server: condition: service_healthy
2025-04-02T09:57:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Docker pull from latest stable tag ### 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. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Web Docker Image was not working properly <img width="1043" alt="Screenshot 2025-04-02 at 3 40 52 PM" src="https://github.com/user-attachments/assets/514b49c8-6a63-4c5b-934b-9d2f0709fc5f" /> Now with this fix its working ## How did you test it? Via locally running Docker Image ## 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.113.0
cfe226943dc5b473e88b7830c54ac73a943ba04b
cfe226943dc5b473e88b7830c54ac73a943ba04b
juspay/hyperswitch
juspay__hyperswitch-7696
Bug: Modify API doc Auth for Profile - Delete Need to update the API doc to display Admin API Key instead of API key for Profile - Delete.
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 8ce45e57a5a..7d364fa972c 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -3324,7 +3324,7 @@ }, "security": [ { - "api_key": [] + "admin_api_key": [] } ] } diff --git a/crates/openapi/src/routes/profile.rs b/crates/openapi/src/routes/profile.rs index 2b72375f988..e2dfffa2d1f 100644 --- a/crates/openapi/src/routes/profile.rs +++ b/crates/openapi/src/routes/profile.rs @@ -108,7 +108,7 @@ pub async fn profile_retrieve() {} ), tag = "Profile", operation_id = "Delete the Profile", - security(("api_key" = [])) + security(("admin_api_key" = [])) )] pub async fn profile_delete() {}
2025-04-02T09:16:22Z
## 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 --> Need to update the API doc to display Admin API Key instead of API key for Profile - Delete. ### 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). --> Correct Information to be displayed in the API docs. ## 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)? --> Cannot be tested. ## 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.113.0
cfe226943dc5b473e88b7830c54ac73a943ba04b
cfe226943dc5b473e88b7830c54ac73a943ba04b
juspay/hyperswitch
juspay__hyperswitch-7715
Bug: refactor(NMI,PAYONE) , Move files from router to hyperswitch connectors Move the connectors from routers to hyperswitch_connectors
diff --git a/Cargo.lock b/Cargo.lock index ea92a99a2c3..068bb1cecb7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3870,6 +3870,7 @@ dependencies = [ "serde", "serde_json", "serde_qs", + "serde_repr", "serde_urlencoded", "serde_with", "sha1", @@ -6535,7 +6536,6 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_qs", - "serde_repr", "serde_urlencoded", "serde_with", "serial_test", diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml index 0d981bf35ba..b8b74ae272a 100644 --- a/crates/hyperswitch_connectors/Cargo.toml +++ b/crates/hyperswitch_connectors/Cargo.toml @@ -36,6 +36,7 @@ roxmltree = "0.19.0" serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" serde_qs = "0.12.0" +serde_repr = "0.1.19" serde_urlencoded = "0.7.1" serde_with = "3.7.0" sha1 = { version = "0.10.6" } diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 93db897bfaf..80e1253940b 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -47,6 +47,7 @@ pub mod moneris; pub mod multisafepay; pub mod nexinets; pub mod nexixpay; +pub mod nmi; pub mod nomupay; pub mod noon; pub mod novalnet; @@ -56,6 +57,7 @@ pub mod opennode; pub mod paybox; pub mod payeezy; pub mod payme; +pub mod payone; pub mod paypal; pub mod paystack; pub mod payu; @@ -66,6 +68,7 @@ pub mod rapyd; pub mod razorpay; pub mod recurly; pub mod redsys; +pub mod riskified; pub mod shift4; pub mod square; pub mod stax; @@ -82,7 +85,6 @@ pub mod worldpay; pub mod xendit; pub mod zen; pub mod zsl; - pub use self::{ aci::Aci, adyen::Adyen, airwallex::Airwallex, amazonpay::Amazonpay, authorizedotnet::Authorizedotnet, bambora::Bambora, bamboraapac::Bamboraapac, @@ -96,13 +98,13 @@ pub use self::{ helcim::Helcim, hipay::Hipay, iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, juspaythreedsserver::Juspaythreedsserver, klarna::Klarna, mifinity::Mifinity, mollie::Mollie, moneris::Moneris, multisafepay::Multisafepay, - nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, noon::Noon, novalnet::Novalnet, - nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, - paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, powertranz::Powertranz, - prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, - shift4::Shift4, square::Square, stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar, - thunes::Thunes, trustpay::Trustpay, tsys::Tsys, - unified_authentication_service::UnifiedAuthenticationService, volt::Volt, - wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen, - zsl::Zsl, + nexinets::Nexinets, nexixpay::Nexixpay, nmi::Nmi, nomupay::Nomupay, noon::Noon, + novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, + payeezy::Payeezy, payme::Payme, payone::Payone, paypal::Paypal, paystack::Paystack, payu::Payu, + placetopay::Placetopay, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, + razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, shift4::Shift4, + square::Square, stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar, thunes::Thunes, + trustpay::Trustpay, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, + volt::Volt, wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, + zen::Zen, zsl::Zsl, }; diff --git a/crates/router/src/connector/nmi.rs b/crates/hyperswitch_connectors/src/connectors/nmi.rs similarity index 51% rename from crates/router/src/connector/nmi.rs rename to crates/hyperswitch_connectors/src/connectors/nmi.rs index 575f4b136eb..b2037c45256 100644 --- a/crates/router/src/connector/nmi.rs +++ b/crates/hyperswitch_connectors/src/connectors/nmi.rs @@ -1,31 +1,54 @@ pub mod transformers; - +use api_models::webhooks::IncomingWebhookEvent; +use common_enums::{enums, CallConnectorAction, PaymentAction}; use common_utils::{ crypto, + errors::CustomResult, ext_traits::ByteSliceExt, - request::RequestContent, + request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; -use diesel_models::enums; use error_stack::{report, ResultExt}; -use regex::Regex; -use transformers as nmi; - -use super::utils as connector_utils; -use crate::{ - configs::settings, - core::{ - errors::{self, CustomResult}, - payments, +use hyperswitch_domain_models::{ + router_data::{AccessToken, ErrorResponse, RouterData}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, CompleteAuthorize, Execute, PSync, PaymentMethodToken, + PreProcessing, RSync, Session, SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, + PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, + PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, + ConnectorSpecifications, ConnectorValidation, + }, + configs::Connectors, + errors::ConnectorError, events::connector_api_logs::ConnectorEvent, - services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - transformers::ForeignFrom, - ErrorResponse, + PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType, + PaymentsPreProcessingType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, + RefundSyncType, Response, }, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +use masking::Maskable; +use regex::Regex; +use transformers as nmi; + +use crate::{ + types::ResponseRouterData, + utils::{construct_not_supported_error_report, convert_amount, get_header_key_value}, }; #[derive(Clone)] @@ -60,9 +83,9 @@ where { fn build_headers( &self, - _req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + _req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { Ok(vec![( "Content-Type".to_string(), "application/x-www-form-urlencoded".to_string().into(), @@ -79,19 +102,19 @@ impl ConnectorCommon for Nmi { api::CurrencyUnit::Base } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.nmi.base_url.as_ref() } fn build_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: nmi::StandardResponse = res .response .parse_struct("StandardResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -116,94 +139,78 @@ impl ConnectorValidation for Nmi { capture_method: Option<enums::CaptureMethod>, _payment_method: enums::PaymentMethod, _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { + ) -> CustomResult<(), ConnectorError> { let capture_method = capture_method.unwrap_or_default(); match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual | enums::CaptureMethod::SequentialAutomatic => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), + construct_not_supported_error_report(capture_method, self.id()), ), } } fn validate_psync_reference_id( &self, - _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + _data: &PaymentsSyncData, _is_three_ds: bool, _status: enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, - ) -> CustomResult<(), errors::ConnectorError> { + ) -> CustomResult<(), ConnectorError> { // in case we dont have transaction id, we can make psync using attempt id Ok(()) } } -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Nmi -{ -} - -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Nmi { } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Nmi -{ -} +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nmi {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Nmi -{ +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nmi {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nmi { fn get_headers( &self, - req: &types::SetupMandateRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &SetupMandateRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::SetupMandateRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &SetupMandateRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::SetupMandateRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &SetupMandateRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = nmi::NmiPaymentsRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - _req: &types::SetupMandateRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("Setup Mandate flow for Nmi".to_string()).into()) + _req: &SetupMandateRouterData, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Err(ConnectorError::NotImplemented("Setup Mandate flow for Nmi".to_string()).into()) // Ok(Some( - // services::RequestBuilder::new() - // .method(services::Method::Post) - // .url(&types::SetupMandateType::get_url(self, req, connectors)?) - // .headers(types::SetupMandateType::get_headers(self, req, connectors)?) - // .set_body(types::SetupMandateType::get_request_body( + // RequestBuilder::new() + // .method(Method::Post) + // .url(&SetupMandateType::get_url(self, req, connectors)?) + // .headers(SetupMandateType::get_headers(self, req, connectors)?) + // .set_body(SetupMandateType::get_request_body( // self, req, connectors, // )?) // .build(), @@ -212,15 +219,15 @@ impl fn handle_response( &self, - data: &types::SetupMandateRouterData, + data: &SetupMandateRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<SetupMandateRouterData, ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -229,27 +236,21 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl api::PaymentsPreProcessing for Nmi {} -impl - ConnectorIntegration< - api::PreProcessing, - types::PaymentsPreProcessingData, - types::PaymentsResponseData, - > for Nmi -{ +impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> for Nmi { fn get_headers( &self, - req: &types::PaymentsPreProcessingRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsPreProcessingRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -259,37 +260,35 @@ impl fn get_url( &self, - _req: &types::PaymentsPreProcessingRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsPreProcessingRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsPreProcessingRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PaymentsPreProcessingRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = nmi::NmiVaultRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsPreProcessingRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsPreProcessingRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { let req = Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .attach_default_headers() - .headers(types::PaymentsPreProcessingType::get_headers( - self, req, connectors, - )?) - .url(&types::PaymentsPreProcessingType::get_url( + .headers(PaymentsPreProcessingType::get_headers( self, req, connectors, )?) - .set_body(types::PaymentsPreProcessingType::get_request_body( + .url(&PaymentsPreProcessingType::get_url(self, req, connectors)?) + .set_body(PaymentsPreProcessingType::get_request_body( self, req, connectors, )?) .build(), @@ -299,15 +298,15 @@ impl fn handle_response( &self, - data: &types::PaymentsPreProcessingRouterData, + data: &PaymentsPreProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsPreProcessingRouterData, ConnectorError> { let response: nmi::NmiVaultResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -316,38 +315,36 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Nmi -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nmi { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, @@ -359,19 +356,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -380,15 +373,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -397,27 +390,21 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl api::PaymentsCompleteAuthorize for Nmi {} -impl - ConnectorIntegration< - api::CompleteAuthorize, - types::CompleteAuthorizeData, - types::PaymentsResponseData, - > for Nmi -{ +impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> for Nmi { fn get_headers( &self, - req: &types::PaymentsCompleteAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCompleteAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { @@ -425,17 +412,17 @@ impl } fn get_url( &self, - _req: &types::PaymentsCompleteAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsCompleteAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsCompleteAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( + req: &PaymentsCompleteAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, @@ -446,20 +433,20 @@ impl } fn build_request( &self, - req: &types::PaymentsCompleteAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCompleteAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsCompleteAuthorizeType::get_url( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsCompleteAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() - .headers(types::PaymentsCompleteAuthorizeType::get_headers( + .headers(PaymentsCompleteAuthorizeType::get_headers( self, req, connectors, )?) - .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( + .set_body(PaymentsCompleteAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -468,15 +455,15 @@ impl fn handle_response( &self, - data: &types::PaymentsCompleteAuthorizeRouterData, + data: &PaymentsCompleteAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, ConnectorError> { let response: nmi::NmiCompleteResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -485,69 +472,65 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Nmi -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nmi { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/query.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = nmi::NmiSyncRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) - .set_body(types::PaymentsSyncType::get_request_body( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) + .set_body(PaymentsSyncType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, ConnectorError> { let response = nmi::SyncResponse::try_from(res.response.to_vec())?; event_builder.map(|i| i.set_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -556,38 +539,36 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Nmi -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nmi { fn get_headers( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( + req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let amount = convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, @@ -599,17 +580,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn build_request( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) - .headers(types::PaymentsCaptureType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsCaptureType::get_request_body( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsCaptureType::get_url(self, req, connectors)?) + .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) + .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), @@ -618,15 +597,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, - data: &types::PaymentsCaptureRouterData, + data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -635,69 +614,65 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Nmi -{ +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nmi { fn get_headers( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsCancelRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = nmi::NmiCancelRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) - .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) - .set_body(types::PaymentsVoidType::get_request_body( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsVoidType::get_url(self, req, connectors)?) + .headers(PaymentsVoidType::get_headers(self, req, connectors)?) + .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsCancelRouterData, + data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsCancelRouterData, ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -706,36 +681,36 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Nmi { +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nmi { fn get_headers( &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let refund_amount = connector_utils::convert_amount( + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let refund_amount = convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, @@ -748,34 +723,30 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn build_request( &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::RefundExecuteType::get_url(self, req, connectors)?) - .headers(types::RefundExecuteType::get_headers( - self, req, connectors, - )?) - .set_body(types::RefundExecuteType::get_request_body( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&RefundExecuteType::get_url(self, req, connectors)?) + .headers(RefundExecuteType::get_headers(self, req, connectors)?) + .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::RefundsRouterData<api::Execute>, + data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<RefundsRouterData<Execute>, ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -784,68 +755,66 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Nmi { +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nmi { fn get_headers( &self, - req: &types::RefundsRouterData<api::RSync>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundsRouterData<RSync>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, - _req: &types::RefundsRouterData<api::RSync>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &RefundsRouterData<RSync>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}api/query.php", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::RefundsRouterData<api::RSync>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &RefundsRouterData<RSync>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = nmi::NmiSyncRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::RefundsRouterData<api::RSync>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &RefundsRouterData<RSync>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::RefundSyncType::get_url(self, req, connectors)?) - .headers(types::RefundSyncType::get_headers(self, req, connectors)?) - .set_body(types::RefundSyncType::get_request_body( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&RefundSyncType::get_url(self, req, connectors)?) + .headers(RefundSyncType::get_headers(self, req, connectors)?) + .set_body(RefundSyncType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::RefundsRouterData<api::RSync>, + data: &RefundsRouterData<RSync>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<RefundsRouterData<RSync>, ConnectorError> { let response = nmi::NmiRefundSyncResponse::try_from(res.response.to_vec())?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -854,81 +823,79 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] -impl api::IncomingWebhook for Nmi { +impl IncomingWebhook for Nmi { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - let sig_header = - connector_utils::get_header_key_value("webhook-signature", request.headers)?; + ) -> CustomResult<Vec<u8>, ConnectorError> { + let sig_header = get_header_key_value("webhook-signature", request.headers)?; let regex_pattern = r"t=(.*),s=(.*)"; if let Some(captures) = Regex::new(regex_pattern) - .change_context(errors::ConnectorError::WebhookSignatureNotFound)? + .change_context(ConnectorError::WebhookSignatureNotFound)? .captures(sig_header) { let signature = captures .get(1) - .ok_or(errors::ConnectorError::WebhookSignatureNotFound)? + .ok_or(ConnectorError::WebhookSignatureNotFound)? .as_str(); return Ok(signature.as_bytes().to_vec()); } - Err(report!(errors::ConnectorError::WebhookSignatureNotFound)) + Err(report!(ConnectorError::WebhookSignatureNotFound)) } fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - let sig_header = - connector_utils::get_header_key_value("webhook-signature", request.headers)?; + ) -> CustomResult<Vec<u8>, ConnectorError> { + let sig_header = get_header_key_value("webhook-signature", request.headers)?; let regex_pattern = r"t=(.*),s=(.*)"; if let Some(captures) = Regex::new(regex_pattern) - .change_context(errors::ConnectorError::WebhookSignatureNotFound)? + .change_context(ConnectorError::WebhookSignatureNotFound)? .captures(sig_header) { let nonce = captures .get(0) - .ok_or(errors::ConnectorError::WebhookSignatureNotFound)? + .ok_or(ConnectorError::WebhookSignatureNotFound)? .as_str(); let message = format!("{}.{}", nonce, String::from_utf8_lossy(request.body)); return Ok(message.into_bytes()); } - Err(report!(errors::ConnectorError::WebhookSignatureNotFound)) + Err(report!(ConnectorError::WebhookSignatureNotFound)) } fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> { let reference_body: nmi::NmiWebhookObjectReference = request .body .parse_struct("nmi NmiWebhookObjectReference") - .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + .change_context(ConnectorError::WebhookResourceObjectNotFound)?; let object_reference_id = match reference_body.event_body.action.action_type { nmi::NmiActionType::Sale => api_models::webhooks::ObjectReferenceId::PaymentId( @@ -954,7 +921,7 @@ impl api::IncomingWebhook for Nmi { nmi::NmiActionType::Refund => api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::RefundId(reference_body.event_body.order_id), ), - _ => Err(errors::ConnectorError::WebhooksNotImplemented)?, + _ => Err(ConnectorError::WebhooksNotImplemented)?, }; Ok(object_reference_id) @@ -962,26 +929,26 @@ impl api::IncomingWebhook for Nmi { fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { let event_type_body: nmi::NmiWebhookEventBody = request .body .parse_struct("nmi NmiWebhookEventType") - .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + .change_context(ConnectorError::WebhookResourceObjectNotFound)?; - Ok(api::IncomingWebhookEvent::foreign_from( + Ok(transformers::get_nmi_webhook_event( event_type_body.event_type, )) } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { let webhook_body: nmi::NmiWebhookBody = request .body .parse_struct("nmi NmiWebhookBody") - .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + .change_context(ConnectorError::WebhookResourceObjectNotFound)?; match webhook_body.event_body.action.action_type { nmi::NmiActionType::Sale @@ -996,33 +963,32 @@ impl api::IncomingWebhook for Nmi { } } -impl services::ConnectorRedirectResponse for Nmi { +impl ConnectorRedirectResponse for Nmi { fn get_flow_type( &self, _query_params: &str, json_payload: Option<serde_json::Value>, - action: services::PaymentAction, - ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + action: PaymentAction, + ) -> CustomResult<CallConnectorAction, ConnectorError> { match action { - services::PaymentAction::CompleteAuthorize => { - let payload_data = - json_payload.ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "connector_metadata", - })?; + PaymentAction::CompleteAuthorize => { + let payload_data = json_payload.ok_or(ConnectorError::MissingRequiredField { + field_name: "connector_metadata", + })?; let redirect_res: nmi::NmiRedirectResponse = serde_json::from_value(payload_data) .change_context( - errors::ConnectorError::MissingConnectorRedirectionPayload { + ConnectorError::MissingConnectorRedirectionPayload { field_name: "redirect_res", }, )?; match redirect_res { transformers::NmiRedirectResponse::NmiRedirectResponseData(_) => { - Ok(payments::CallConnectorAction::Trigger) + Ok(CallConnectorAction::Trigger) } transformers::NmiRedirectResponse::NmiErrorResponseData(error_res) => { - Ok(payments::CallConnectorAction::StatusUpdate { + Ok(CallConnectorAction::StatusUpdate { status: enums::AttemptStatus::Failure, error_code: Some(error_res.code), error_message: Some(error_res.message), @@ -1030,9 +996,8 @@ impl services::ConnectorRedirectResponse for Nmi { } } } - services::PaymentAction::PSync - | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => { - Ok(payments::CallConnectorAction::Trigger) + PaymentAction::PSync | PaymentAction::PaymentAuthenticateCompleteAuthorize => { + Ok(CallConnectorAction::Trigger) } } } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs similarity index 62% rename from crates/router/src/connector/nmi/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs index da1231d1d8c..c8dbea3844d 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs @@ -1,22 +1,43 @@ -use api_models::webhooks; +use api_models::webhooks::IncomingWebhookEvent; use cards::CardNumber; -use common_enums::CountryAlpha2; +use common_enums::{ + AttemptStatus, AuthenticationType, CaptureMethod, CountryAlpha2, Currency, RefundStatus, +}; use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii::Email, types::FloatMajorUnit}; use error_stack::{report, Report, ResultExt}; +use hyperswitch_domain_models::{ + payment_method_data::{ + ApplePayWalletData, Card, GooglePayWalletData, PaymentMethodData, WalletData, + }, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + Authorize, Capture, CompleteAuthorize, Execute, PreProcessing, RSync, SetupMandate, Void, + }, + router_request_types::{ + CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, + PaymentsPreProcessingData, ResponseId, + }, + router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, + }, +}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{ - self, AddressDetailsData, PaymentsAuthorizeRequestData, - PaymentsCompleteAuthorizeRequestData, RouterData, + types::{PaymentsResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, + utils::{ + get_unimplemented_payment_method_error_message, to_currency_base_unit_asf64, + AddressDetailsData as _, CardData as _, PaymentsAuthorizeRequestData, + PaymentsCompleteAuthorizeRequestData as _, RouterData as _, }, - core::errors, - services, - types::{self, api, domain, storage::enums, transformers::ForeignFrom, ConnectorAuthType}, }; -type Error = Report<errors::ConnectorError>; +type Error = Report<ConnectorError>; #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] @@ -46,7 +67,7 @@ impl TryFrom<&ConnectorAuthType> for NmiAuthType { api_key: api_key.to_owned(), public_key: Some(key1.to_owned()), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } @@ -90,9 +111,9 @@ pub enum CustomerAction { UpdateCustomer, } -impl TryFrom<&types::PaymentsPreProcessingRouterData> for NmiVaultRequest { +impl TryFrom<&PaymentsPreProcessingRouterData> for NmiVaultRequest { type Error = Error; - fn try_from(item: &types::PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; let (ccnumber, ccexp, cvv) = get_card_details(item.request.payment_method_data.clone())?; let billing_details = item.get_billing_address()?; @@ -120,21 +141,18 @@ impl TryFrom<&types::PaymentsPreProcessingRouterData> for NmiVaultRequest { } fn get_card_details( - payment_method_data: Option<domain::PaymentMethodData>, -) -> CustomResult<(CardNumber, Secret<String>, Secret<String>), errors::ConnectorError> { + payment_method_data: Option<PaymentMethodData>, +) -> CustomResult<(CardNumber, Secret<String>, Secret<String>), ConnectorError> { match payment_method_data { - Some(domain::PaymentMethodData::Card(ref card_details)) => Ok(( + Some(PaymentMethodData::Card(ref card_details)) => Ok(( card_details.card_number.clone(), - utils::CardData::get_card_expiry_month_year_2_digit_with_delimiter( - card_details, - "".to_string(), - )?, + card_details.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?, card_details.card_cvc.clone(), )), - _ => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Nmi"), - ) - .into()), + _ => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message("Nmi")) + .into(), + ), } } @@ -149,59 +167,56 @@ pub struct NmiVaultResponse { impl TryFrom< - types::ResponseRouterData< - api::PreProcessing, + ResponseRouterData< + PreProcessing, NmiVaultResponse, - types::PaymentsPreProcessingData, - types::PaymentsResponseData, + PaymentsPreProcessingData, + PaymentsResponseData, >, - > for types::PaymentsPreProcessingRouterData + > for PaymentsPreProcessingRouterData { type Error = Error; fn try_from( - item: types::ResponseRouterData< - api::PreProcessing, + item: ResponseRouterData< + PreProcessing, NmiVaultResponse, - types::PaymentsPreProcessingData, - types::PaymentsResponseData, + PaymentsPreProcessingData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.data.connector_auth_type).try_into()?; - let amount_data = - item.data - .request - .amount - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "amount", - })?; + let amount_data = item + .data + .request + .amount + .ok_or(ConnectorError::MissingRequiredField { + field_name: "amount", + })?; let currency_data = item.data .request .currency - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "currency", })?; let (response, status) = match item.response.response { Response::Approved => ( - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::NoResponseId, - redirection_data: Box::new(Some(services::RedirectForm::Nmi { - amount: utils::to_currency_base_unit_asf64( - amount_data, - currency_data.to_owned(), - )? - .to_string(), + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::NoResponseId, + redirection_data: Box::new(Some(RedirectForm::Nmi { + amount: to_currency_base_unit_asf64(amount_data, currency_data.to_owned())? + .to_string(), currency: currency_data, customer_vault_id: item .response .customer_vault_id - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "customer_vault_id", })? .peek() .to_string(), public_key: auth_type.public_key.ok_or( - errors::ConnectorError::InvalidConnectorConfig { + ConnectorError::InvalidConnectorConfig { config: "public_key", }, )?, @@ -214,10 +229,10 @@ impl incremental_authorization_allowed: None, charges: None, }), - enums::AttemptStatus::AuthenticationPending, + AttemptStatus::AuthenticationPending, ), Response::Declined | Response::Error => ( - Err(types::ErrorResponse { + Err(ErrorResponse { code: item.response.response_code, message: item.response.responsetext.to_owned(), reason: Some(item.response.responsetext), @@ -228,7 +243,7 @@ impl network_decline_code: None, network_error_message: None, }), - enums::AttemptStatus::Failure, + AttemptStatus::Failure, ), }; Ok(Self { @@ -285,10 +300,10 @@ pub struct NmiRedirectResponseData { customer_vault_id: Secret<String>, } -impl TryFrom<&NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for NmiCompleteRequest { +impl TryFrom<&NmiRouterData<&PaymentsCompleteAuthorizeRouterData>> for NmiCompleteRequest { type Error = Error; fn try_from( - item: &NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + item: &NmiRouterData<&PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let transaction_type = match item.router_data.request.is_auto_capture()? { true => TransactionType::Sale, @@ -302,7 +317,7 @@ impl TryFrom<&NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for Nm .expose(); let three_ds_data: NmiRedirectResponseData = serde_json::from_value(payload_data) - .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload { + .change_context(ConnectorError::MissingConnectorRedirectionPayload { field_name: "three_ds_data", })?; @@ -340,29 +355,27 @@ pub struct NmiCompleteResponse { impl TryFrom< - types::ResponseRouterData< - api::CompleteAuthorize, + ResponseRouterData< + CompleteAuthorize, NmiCompleteResponse, - types::CompleteAuthorizeData, - types::PaymentsResponseData, + CompleteAuthorizeData, + PaymentsResponseData, >, - > for types::PaymentsCompleteAuthorizeRouterData + > for PaymentsCompleteAuthorizeRouterData { type Error = Error; fn try_from( - item: types::ResponseRouterData< - api::CompleteAuthorize, + item: ResponseRouterData< + CompleteAuthorize, NmiCompleteResponse, - types::CompleteAuthorizeData, - types::PaymentsResponseData, + CompleteAuthorizeData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transactionid, - ), + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.transactionid), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, @@ -371,20 +384,15 @@ impl incremental_authorization_allowed: None, charges: None, }), - if let Some(diesel_models::enums::CaptureMethod::Automatic) = - item.data.request.capture_method - { - enums::AttemptStatus::CaptureInitiated + if let Some(CaptureMethod::Automatic) = item.data.request.capture_method { + AttemptStatus::CaptureInitiated } else { - enums::AttemptStatus::Authorizing + AttemptStatus::Authorizing }, ), Response::Declined | Response::Error => ( - Err(types::ErrorResponse::foreign_from(( - item.response, - item.http_code, - ))), - enums::AttemptStatus::Failure, + Err(get_nmi_error_response(item.response, item.http_code)), + AttemptStatus::Failure, ), }; Ok(Self { @@ -395,19 +403,17 @@ impl } } -impl ForeignFrom<(NmiCompleteResponse, u16)> for types::ErrorResponse { - fn foreign_from((response, http_code): (NmiCompleteResponse, u16)) -> Self { - Self { - code: response.response_code, - message: response.responsetext.to_owned(), - reason: Some(response.responsetext), - status_code: http_code, - attempt_status: None, - connector_transaction_id: Some(response.transactionid), - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - } +fn get_nmi_error_response(response: NmiCompleteResponse, http_code: u16) -> ErrorResponse { + ErrorResponse { + code: response.response_code, + message: response.responsetext.to_owned(), + reason: Some(response.responsetext), + status_code: http_code, + attempt_status: None, + connector_transaction_id: Some(response.transactionid), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, } } @@ -417,7 +423,7 @@ pub struct NmiPaymentsRequest { transaction_type: TransactionType, amount: FloatMajorUnit, security_key: Secret<String>, - currency: enums::Currency, + currency: Currency, #[serde(flatten)] payment_method: PaymentMethod, #[serde(flatten)] @@ -488,11 +494,9 @@ pub struct ApplePayData { applepay_payment_data: Secret<String>, } -impl TryFrom<&NmiRouterData<&types::PaymentsAuthorizeRouterData>> for NmiPaymentsRequest { +impl TryFrom<&NmiRouterData<&PaymentsAuthorizeRouterData>> for NmiPaymentsRequest { type Error = Error; - fn try_from( - item: &NmiRouterData<&types::PaymentsAuthorizeRouterData>, - ) -> Result<Self, Self::Error> { + fn try_from(item: &NmiRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> { let transaction_type = match item.router_data.request.is_auto_capture()? { true => TransactionType::Sale, false => TransactionType::Auth, @@ -521,102 +525,85 @@ impl TryFrom<&NmiRouterData<&types::PaymentsAuthorizeRouterData>> for NmiPayment } } -impl - TryFrom<( - &domain::PaymentMethodData, - Option<&types::PaymentsAuthorizeRouterData>, - )> for PaymentMethod -{ +impl TryFrom<(&PaymentMethodData, Option<&PaymentsAuthorizeRouterData>)> for PaymentMethod { type Error = Error; fn try_from( - item: ( - &domain::PaymentMethodData, - Option<&types::PaymentsAuthorizeRouterData>, - ), + item: (&PaymentMethodData, Option<&PaymentsAuthorizeRouterData>), ) -> Result<Self, Self::Error> { let (payment_method_data, router_data) = item; match payment_method_data { - domain::PaymentMethodData::Card(ref card) => match router_data { + PaymentMethodData::Card(ref card) => match router_data { Some(data) => match data.auth_type { - common_enums::AuthenticationType::NoThreeDs => Ok(Self::try_from(card)?), - common_enums::AuthenticationType::ThreeDs => { - Ok(Self::try_from((card, &data.request))?) - } + AuthenticationType::NoThreeDs => Ok(Self::try_from(card)?), + AuthenticationType::ThreeDs => Ok(Self::try_from((card, &data.request))?), }, None => Ok(Self::try_from(card)?), }, - domain::PaymentMethodData::Wallet(ref wallet_type) => match wallet_type { - domain::WalletData::GooglePay(ref googlepay_data) => Ok(Self::from(googlepay_data)), - domain::WalletData::ApplePay(ref applepay_data) => Ok(Self::from(applepay_data)), - domain::WalletData::AliPayQr(_) - | domain::WalletData::AliPayRedirect(_) - | domain::WalletData::AliPayHkRedirect(_) - | domain::WalletData::AmazonPayRedirect(_) - | domain::WalletData::MomoRedirect(_) - | domain::WalletData::KakaoPayRedirect(_) - | domain::WalletData::GoPayRedirect(_) - | domain::WalletData::GcashRedirect(_) - | domain::WalletData::ApplePayRedirect(_) - | domain::WalletData::ApplePayThirdPartySdk(_) - | domain::WalletData::DanaRedirect {} - | domain::WalletData::GooglePayRedirect(_) - | domain::WalletData::GooglePayThirdPartySdk(_) - | domain::WalletData::MbWayRedirect(_) - | domain::WalletData::MobilePayRedirect(_) - | domain::WalletData::PaypalRedirect(_) - | domain::WalletData::PaypalSdk(_) - | domain::WalletData::Paze(_) - | domain::WalletData::SamsungPay(_) - | domain::WalletData::TwintRedirect {} - | domain::WalletData::VippsRedirect {} - | domain::WalletData::TouchNGoRedirect(_) - | domain::WalletData::WeChatPayRedirect(_) - | domain::WalletData::WeChatPayQr(_) - | domain::WalletData::CashappQr(_) - | domain::WalletData::SwishQr(_) - | domain::WalletData::Mifinity(_) => { - Err(report!(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("nmi"), - ))) - } + PaymentMethodData::Wallet(ref wallet_type) => match wallet_type { + WalletData::GooglePay(ref googlepay_data) => Ok(Self::from(googlepay_data)), + WalletData::ApplePay(ref applepay_data) => Ok(Self::from(applepay_data)), + WalletData::AliPayQr(_) + | WalletData::AliPayRedirect(_) + | WalletData::AliPayHkRedirect(_) + | WalletData::AmazonPayRedirect(_) + | WalletData::MomoRedirect(_) + | WalletData::KakaoPayRedirect(_) + | WalletData::GoPayRedirect(_) + | WalletData::GcashRedirect(_) + | WalletData::ApplePayRedirect(_) + | WalletData::ApplePayThirdPartySdk(_) + | WalletData::DanaRedirect {} + | WalletData::GooglePayRedirect(_) + | WalletData::GooglePayThirdPartySdk(_) + | WalletData::MbWayRedirect(_) + | WalletData::MobilePayRedirect(_) + | WalletData::PaypalRedirect(_) + | WalletData::PaypalSdk(_) + | WalletData::Paze(_) + | WalletData::SamsungPay(_) + | WalletData::TwintRedirect {} + | WalletData::VippsRedirect {} + | WalletData::TouchNGoRedirect(_) + | WalletData::WeChatPayRedirect(_) + | WalletData::WeChatPayQr(_) + | WalletData::CashappQr(_) + | WalletData::SwishQr(_) + | WalletData::Mifinity(_) => Err(report!(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("nmi"), + ))), }, - domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::MobilePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) - | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("nmi"), - ) - .into()) - } + PaymentMethodData::CardRedirect(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( + "nmi", + )) + .into(), + ), } } } -impl TryFrom<(&domain::payments::Card, &types::PaymentsAuthorizeData)> for PaymentMethod { +impl TryFrom<(&Card, &PaymentsAuthorizeData)> for PaymentMethod { type Error = Error; - fn try_from( - val: (&domain::payments::Card, &types::PaymentsAuthorizeData), - ) -> Result<Self, Self::Error> { + fn try_from(val: (&Card, &PaymentsAuthorizeData)) -> Result<Self, Self::Error> { let (card_data, item) = val; let auth_data = &item.get_authentication_data()?; - let ccexp = utils::CardData::get_card_expiry_month_year_2_digit_with_delimiter( - card_data, - "".to_string(), - )?; + let ccexp = card_data.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?; let card_3ds_details = CardThreeDsData { ccnumber: card_data.card_number.clone(), @@ -640,13 +627,10 @@ impl TryFrom<(&domain::payments::Card, &types::PaymentsAuthorizeData)> for Payme } } -impl TryFrom<&domain::payments::Card> for PaymentMethod { +impl TryFrom<&Card> for PaymentMethod { type Error = Error; - fn try_from(card: &domain::payments::Card) -> Result<Self, Self::Error> { - let ccexp = utils::CardData::get_card_expiry_month_year_2_digit_with_delimiter( - card, - "".to_string(), - )?; + fn try_from(card: &Card) -> Result<Self, Self::Error> { + let ccexp = card.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?; let card = CardData { ccnumber: card.card_number.clone(), ccexp, @@ -656,8 +640,8 @@ impl TryFrom<&domain::payments::Card> for PaymentMethod { } } -impl From<&domain::GooglePayWalletData> for PaymentMethod { - fn from(wallet_data: &domain::GooglePayWalletData) -> Self { +impl From<&GooglePayWalletData> for PaymentMethod { + fn from(wallet_data: &GooglePayWalletData) -> Self { let gpay_data = GooglePayData { googlepay_payment_data: Secret::new(wallet_data.tokenization_data.token.clone()), }; @@ -665,8 +649,8 @@ impl From<&domain::GooglePayWalletData> for PaymentMethod { } } -impl From<&domain::ApplePayWalletData> for PaymentMethod { - fn from(wallet_data: &domain::ApplePayWalletData) -> Self { +impl From<&ApplePayWalletData> for PaymentMethod { + fn from(wallet_data: &ApplePayWalletData) -> Self { let apple_pay_data = ApplePayData { applepay_payment_data: Secret::new(wallet_data.payment_data.clone()), }; @@ -674,9 +658,9 @@ impl From<&domain::ApplePayWalletData> for PaymentMethod { } } -impl TryFrom<&types::SetupMandateRouterData> for NmiPaymentsRequest { +impl TryFrom<&SetupMandateRouterData> for NmiPaymentsRequest { type Error = Error; - fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; let payment_method = PaymentMethod::try_from((&item.request.payment_method_data, None))?; Ok(Self { @@ -697,9 +681,9 @@ pub struct NmiSyncRequest { pub security_key: Secret<String>, } -impl TryFrom<&types::PaymentsSyncRouterData> for NmiSyncRequest { +impl TryFrom<&PaymentsSyncRouterData> for NmiSyncRequest { type Error = Error; - fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; Ok(Self { security_key: auth.api_key, @@ -717,11 +701,9 @@ pub struct NmiCaptureRequest { pub amount: Option<FloatMajorUnit>, } -impl TryFrom<&NmiRouterData<&types::PaymentsCaptureRouterData>> for NmiCaptureRequest { +impl TryFrom<&NmiRouterData<&PaymentsCaptureRouterData>> for NmiCaptureRequest { type Error = Error; - fn try_from( - item: &NmiRouterData<&types::PaymentsCaptureRouterData>, - ) -> Result<Self, Self::Error> { + fn try_from(item: &NmiRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(Self { transaction_type: TransactionType::Capture, @@ -734,27 +716,22 @@ impl TryFrom<&NmiRouterData<&types::PaymentsCaptureRouterData>> for NmiCaptureRe impl TryFrom< - types::ResponseRouterData< - api::Capture, - StandardResponse, - types::PaymentsCaptureData, - types::PaymentsResponseData, - >, - > for types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + ResponseRouterData<Capture, StandardResponse, PaymentsCaptureData, PaymentsResponseData>, + > for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData> { type Error = Error; fn try_from( - item: types::ResponseRouterData< - api::Capture, + item: ResponseRouterData< + Capture, StandardResponse, - types::PaymentsCaptureData, - types::PaymentsResponseData, + PaymentsCaptureData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.transactionid.to_owned(), ), redirection_data: Box::new(None), @@ -765,14 +742,11 @@ impl incremental_authorization_allowed: None, charges: None, }), - enums::AttemptStatus::CaptureInitiated, + AttemptStatus::CaptureInitiated, ), Response::Declined | Response::Error => ( - Err(types::ErrorResponse::foreign_from(( - item.response, - item.http_code, - ))), - enums::AttemptStatus::CaptureFailed, + Err(get_standard_error_response(item.response, item.http_code)), + AttemptStatus::CaptureFailed, ), }; Ok(Self { @@ -803,14 +777,14 @@ pub enum NmiVoidReason { PosTimeout, } -impl TryFrom<&types::PaymentsCancelRouterData> for NmiCancelRequest { +impl TryFrom<&PaymentsCancelRouterData> for NmiCancelRequest { type Error = Error; - fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; match &item.request.cancellation_reason { Some(cancellation_reason) => { let void_reason: NmiVoidReason = serde_json::from_str(&format!("\"{}\"", cancellation_reason)) - .map_err(|_| errors::ConnectorError::NotSupported { + .map_err(|_| ConnectorError::NotSupported { message: format!("Json deserialise error: unknown variant `{}` expected to be one of `fraud`, `user_cancel`, `icc_rejected`, `icc_card_removed`, `icc_no_confirmation`, `pos_timeout`. This cancellation_reason", cancellation_reason), connector: "nmi" })?; @@ -821,7 +795,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NmiCancelRequest { void_reason, }) } - None => Err(errors::ConnectorError::MissingRequiredField { + None => Err(ConnectorError::MissingRequiredField { field_name: "cancellation_reason", } .into()), @@ -851,29 +825,17 @@ pub struct StandardResponse { pub response_code: String, } -impl<T> - TryFrom< - types::ResponseRouterData< - api::SetupMandate, - StandardResponse, - T, - types::PaymentsResponseData, - >, - > for types::RouterData<api::SetupMandate, T, types::PaymentsResponseData> +impl<T> TryFrom<ResponseRouterData<SetupMandate, StandardResponse, T, PaymentsResponseData>> + for RouterData<SetupMandate, T, PaymentsResponseData> { type Error = Error; fn try_from( - item: types::ResponseRouterData< - api::SetupMandate, - StandardResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<SetupMandate, StandardResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), @@ -884,14 +846,11 @@ impl<T> incremental_authorization_allowed: None, charges: None, }), - enums::AttemptStatus::Charged, + AttemptStatus::Charged, ), Response::Declined | Response::Error => ( - Err(types::ErrorResponse::foreign_from(( - item.response, - item.http_code, - ))), - enums::AttemptStatus::Failure, + Err(get_standard_error_response(item.response, item.http_code)), + AttemptStatus::Failure, ), }; Ok(Self { @@ -901,39 +860,36 @@ impl<T> }) } } - -impl ForeignFrom<(StandardResponse, u16)> for types::ErrorResponse { - fn foreign_from((response, http_code): (StandardResponse, u16)) -> Self { - Self { - code: response.response_code, - message: response.responsetext.to_owned(), - reason: Some(response.responsetext), - status_code: http_code, - attempt_status: None, - connector_transaction_id: Some(response.transactionid), - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - } +fn get_standard_error_response(response: StandardResponse, http_code: u16) -> ErrorResponse { + ErrorResponse { + code: response.response_code, + message: response.responsetext.to_owned(), + reason: Some(response.responsetext), + status_code: http_code, + attempt_status: None, + connector_transaction_id: Some(response.transactionid), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, } } -impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>> - for types::RouterData<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> +impl TryFrom<PaymentsResponseRouterData<StandardResponse>> + for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> { type Error = Error; fn try_from( - item: types::ResponseRouterData< - api::Authorize, + item: ResponseRouterData< + Authorize, StandardResponse, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, + PaymentsAuthorizeData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), @@ -944,20 +900,15 @@ impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>> incremental_authorization_allowed: None, charges: None, }), - if let Some(diesel_models::enums::CaptureMethod::Automatic) = - item.data.request.capture_method - { - enums::AttemptStatus::CaptureInitiated + if let Some(CaptureMethod::Automatic) = item.data.request.capture_method { + AttemptStatus::CaptureInitiated } else { - enums::AttemptStatus::Authorized + AttemptStatus::Authorized }, ), Response::Declined | Response::Error => ( - Err(types::ErrorResponse::foreign_from(( - item.response, - item.http_code, - ))), - enums::AttemptStatus::Failure, + Err(get_standard_error_response(item.response, item.http_code)), + AttemptStatus::Failure, ), }; Ok(Self { @@ -968,23 +919,17 @@ impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>> } } -impl<T> - TryFrom<types::ResponseRouterData<api::Void, StandardResponse, T, types::PaymentsResponseData>> - for types::RouterData<api::Void, T, types::PaymentsResponseData> +impl<T> TryFrom<ResponseRouterData<Void, StandardResponse, T, PaymentsResponseData>> + for RouterData<Void, T, PaymentsResponseData> { type Error = Error; fn try_from( - item: types::ResponseRouterData< - api::Void, - StandardResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<Void, StandardResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), @@ -995,14 +940,11 @@ impl<T> incremental_authorization_allowed: None, charges: None, }), - enums::AttemptStatus::VoidInitiated, + AttemptStatus::VoidInitiated, ), Response::Declined | Response::Error => ( - Err(types::ErrorResponse::foreign_from(( - item.response, - item.http_code, - ))), - enums::AttemptStatus::VoidFailed, + Err(get_standard_error_response(item.response, item.http_code)), + AttemptStatus::VoidFailed, ), }; Ok(Self { @@ -1026,18 +968,18 @@ pub enum NmiStatus { Unknown, } -impl<F, T> TryFrom<types::ResponseRouterData<F, SyncResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, SyncResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = Error; fn try_from( - item: types::ResponseRouterData<F, SyncResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, SyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response.transaction { Some(trn) => Ok(Self { - status: enums::AttemptStatus::from(NmiStatus::from(trn.condition)), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(trn.transaction_id), + status: AttemptStatus::from(NmiStatus::from(trn.condition)), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(trn.transaction_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, @@ -1057,10 +999,10 @@ impl TryFrom<Vec<u8>> for SyncResponse { type Error = Error; fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { let query_response = String::from_utf8(bytes) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; query_response .parse_xml::<Self>() - .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .change_context(ConnectorError::ResponseDeserializationFailed) } } @@ -1068,14 +1010,14 @@ impl TryFrom<Vec<u8>> for NmiRefundSyncResponse { type Error = Error; fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { let query_response = String::from_utf8(bytes) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; query_response .parse_xml::<Self>() - .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .change_context(ConnectorError::ResponseDeserializationFailed) } } -impl From<NmiStatus> for enums::AttemptStatus { +impl From<NmiStatus> for AttemptStatus { fn from(item: NmiStatus) -> Self { match item { NmiStatus::Abandoned => Self::AuthenticationFailed, @@ -1099,9 +1041,9 @@ pub struct NmiRefundRequest { amount: FloatMajorUnit, } -impl<F> TryFrom<&NmiRouterData<&types::RefundsRouterData<F>>> for NmiRefundRequest { +impl<F> TryFrom<&NmiRouterData<&RefundsRouterData<F>>> for NmiRefundRequest { type Error = Error; - fn try_from(item: &NmiRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { + fn try_from(item: &NmiRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?; Ok(Self { transaction_type: TransactionType::Refund, @@ -1113,16 +1055,14 @@ impl<F> TryFrom<&NmiRouterData<&types::RefundsRouterData<F>>> for NmiRefundReque } } -impl TryFrom<types::RefundsResponseRouterData<api::Execute, StandardResponse>> - for types::RefundsRouterData<api::Execute> -{ +impl TryFrom<RefundsResponseRouterData<Execute, StandardResponse>> for RefundsRouterData<Execute> { type Error = Error; fn try_from( - item: types::RefundsResponseRouterData<api::Execute, StandardResponse>, + item: RefundsResponseRouterData<Execute, StandardResponse>, ) -> Result<Self, Self::Error> { - let refund_status = enums::RefundStatus::from(item.response.response); + let refund_status = RefundStatus::from(item.response.response); Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.orderid, refund_status, }), @@ -1131,16 +1071,14 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, StandardResponse>> } } -impl TryFrom<types::RefundsResponseRouterData<api::Capture, StandardResponse>> - for types::RefundsRouterData<api::Capture> -{ +impl TryFrom<RefundsResponseRouterData<Capture, StandardResponse>> for RefundsRouterData<Capture> { type Error = Error; fn try_from( - item: types::RefundsResponseRouterData<api::Capture, StandardResponse>, + item: RefundsResponseRouterData<Capture, StandardResponse>, ) -> Result<Self, Self::Error> { - let refund_status = enums::RefundStatus::from(item.response.response); + let refund_status = RefundStatus::from(item.response.response); Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.transactionid, refund_status, }), @@ -1149,7 +1087,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Capture, StandardResponse>> } } -impl From<Response> for enums::RefundStatus { +impl From<Response> for RefundStatus { fn from(item: Response) -> Self { match item { Response::Approved => Self::Pending, @@ -1158,9 +1096,9 @@ impl From<Response> for enums::RefundStatus { } } -impl TryFrom<&types::RefundSyncRouterData> for NmiSyncRequest { +impl TryFrom<&RefundSyncRouterData> for NmiSyncRequest { type Error = Error; - fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; Ok(Self { @@ -1169,22 +1107,20 @@ impl TryFrom<&types::RefundSyncRouterData> for NmiSyncRequest { .request .connector_refund_id .clone() - .ok_or(errors::ConnectorError::MissingConnectorRefundID)?, + .ok_or(ConnectorError::MissingConnectorRefundID)?, }) } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, NmiRefundSyncResponse>> - for types::RefundsRouterData<api::RSync> -{ - type Error = Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<RSync, NmiRefundSyncResponse>> for RefundsRouterData<RSync> { + type Error = Report<ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, NmiRefundSyncResponse>, + item: RefundsResponseRouterData<RSync, NmiRefundSyncResponse>, ) -> Result<Self, Self::Error> { let refund_status = - enums::RefundStatus::from(NmiStatus::from(item.response.transaction.condition)); + RefundStatus::from(NmiStatus::from(item.response.transaction.condition)); Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.transaction.order_id, refund_status, }), @@ -1193,7 +1129,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, NmiRefundSyncResponse> } } -impl From<NmiStatus> for enums::RefundStatus { +impl From<NmiStatus> for RefundStatus { fn from(item: NmiStatus) -> Self { match item { NmiStatus::Abandoned @@ -1310,25 +1246,23 @@ pub enum NmiWebhookEventType { CaptureUnknown, } -impl ForeignFrom<NmiWebhookEventType> for webhooks::IncomingWebhookEvent { - fn foreign_from(status: NmiWebhookEventType) -> Self { - match status { - NmiWebhookEventType::SaleSuccess => Self::PaymentIntentSuccess, - NmiWebhookEventType::SaleFailure => Self::PaymentIntentFailure, - NmiWebhookEventType::RefundSuccess => Self::RefundSuccess, - NmiWebhookEventType::RefundFailure => Self::RefundFailure, - NmiWebhookEventType::VoidSuccess => Self::PaymentIntentCancelled, - NmiWebhookEventType::AuthSuccess => Self::PaymentIntentAuthorizationSuccess, - NmiWebhookEventType::CaptureSuccess => Self::PaymentIntentCaptureSuccess, - NmiWebhookEventType::AuthFailure => Self::PaymentIntentAuthorizationFailure, - NmiWebhookEventType::CaptureFailure => Self::PaymentIntentCaptureFailure, - NmiWebhookEventType::VoidFailure => Self::PaymentIntentCancelFailure, - NmiWebhookEventType::SaleUnknown - | NmiWebhookEventType::RefundUnknown - | NmiWebhookEventType::AuthUnknown - | NmiWebhookEventType::VoidUnknown - | NmiWebhookEventType::CaptureUnknown => Self::EventNotSupported, - } +pub fn get_nmi_webhook_event(status: NmiWebhookEventType) -> IncomingWebhookEvent { + match status { + NmiWebhookEventType::SaleSuccess => IncomingWebhookEvent::PaymentIntentSuccess, + NmiWebhookEventType::SaleFailure => IncomingWebhookEvent::PaymentIntentFailure, + NmiWebhookEventType::RefundSuccess => IncomingWebhookEvent::RefundSuccess, + NmiWebhookEventType::RefundFailure => IncomingWebhookEvent::RefundFailure, + NmiWebhookEventType::VoidSuccess => IncomingWebhookEvent::PaymentIntentCancelled, + NmiWebhookEventType::AuthSuccess => IncomingWebhookEvent::PaymentIntentAuthorizationSuccess, + NmiWebhookEventType::CaptureSuccess => IncomingWebhookEvent::PaymentIntentCaptureSuccess, + NmiWebhookEventType::AuthFailure => IncomingWebhookEvent::PaymentIntentAuthorizationFailure, + NmiWebhookEventType::CaptureFailure => IncomingWebhookEvent::PaymentIntentCaptureFailure, + NmiWebhookEventType::VoidFailure => IncomingWebhookEvent::PaymentIntentCancelFailure, + NmiWebhookEventType::SaleUnknown + | NmiWebhookEventType::RefundUnknown + | NmiWebhookEventType::AuthUnknown + | NmiWebhookEventType::VoidUnknown + | NmiWebhookEventType::CaptureUnknown => IncomingWebhookEvent::EventNotSupported, } } diff --git a/crates/router/src/connector/payone.rs b/crates/hyperswitch_connectors/src/connectors/payone.rs similarity index 57% rename from crates/router/src/connector/payone.rs rename to crates/hyperswitch_connectors/src/connectors/payone.rs index db862274fe1..ca3e9b2cba9 100644 --- a/crates/router/src/connector/payone.rs +++ b/crates/hyperswitch_connectors/src/connectors/payone.rs @@ -1,44 +1,73 @@ pub mod transformers; +use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use base64::Engine; #[cfg(feature = "payouts")] use common_utils::request::RequestContent; +use common_utils::{consts::BASE64_ENGINE, errors::CustomResult, ext_traits::BytesExt}; #[cfg(feature = "payouts")] -use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector}; +use common_utils::{ + request::{Method, Request, RequestBuilder}, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, +}; use error_stack::{report, ResultExt}; -use masking::{ExposeInterface, PeekInterface}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_data::RouterData, + router_flow_types::PoFulfill, + types::{PayoutsData, PayoutsResponseData, PayoutsRouterData}, +}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, +}; +use hyperswitch_interfaces::{ + api::{ + ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, + ConnectorSpecifications, ConnectorValidation, CurrencyUnit, MandateSetup, Payment, + PaymentAuthorize, PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, + Refund, RefundExecute, RefundSync, + }, + configs::Connectors, + consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, + errors::ConnectorError, + events::connector_api_logs::ConnectorEvent, + types::Response, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::{ + api::{PayoutFulfill, Payouts}, + types::PayoutFulfillType, +}; +use masking::{ExposeInterface, Mask, Maskable, PeekInterface}; use ring::hmac; #[cfg(feature = "payouts")] use router_env::{instrument, tracing}; use self::transformers as payone; #[cfg(feature = "payouts")] -use crate::connector::utils::convert_amount; +use crate::constants::headers::DATE; #[cfg(feature = "payouts")] use crate::get_formatted_date_time; -#[cfg(feature = "payouts")] -use crate::services; use crate::{ - configs::settings, - connector::{ - utils as connector_utils, - utils::{ConnectorErrorType, ConnectorErrorTypeMapping}, - }, - consts, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - request::{self, Mask}, - ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, + constants::headers::AUTHORIZATION, + utils::{ + get_error_code_error_message_based_on_priority, ConnectorErrorType, + ConnectorErrorTypeMapping, }, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, - }, - utils::BytesExt, }; +#[cfg(feature = "payouts")] +use crate::{types::ResponseRouterData, utils::convert_amount}; #[derive(Clone)] pub struct Payone { #[cfg(feature = "payouts")] @@ -59,7 +88,7 @@ impl Payone { canonicalized_path: String, content_type: String, date_header: String, - ) -> CustomResult<String, errors::ConnectorError> { + ) -> CustomResult<String, ConnectorError> { let payone::PayoneAuthType { api_key, api_secret, @@ -73,32 +102,28 @@ impl Payone { canonicalized_path.trim() ); let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.expose().as_bytes()); - let hash_hmac = consts::BASE64_ENGINE.encode(hmac::sign(&key, string_to_hash.as_bytes())); + let hash_hmac = BASE64_ENGINE.encode(hmac::sign(&key, string_to_hash.as_bytes())); let signature_header = format!("GCS v1HMAC:{}:{}", api_key.peek(), hash_hmac); Ok(signature_header) } } -impl api::Payment for Payone {} -impl api::PaymentSession for Payone {} -impl api::ConnectorAccessToken for Payone {} -impl api::MandateSetup for Payone {} -impl api::PaymentAuthorize for Payone {} -impl api::PaymentSync for Payone {} -impl api::PaymentCapture for Payone {} -impl api::PaymentVoid for Payone {} -impl api::Refund for Payone {} -impl api::RefundExecute for Payone {} -impl api::RefundSync for Payone {} -impl api::PaymentToken for Payone {} - -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Payone +impl Payment for Payone {} +impl PaymentSession for Payone {} +impl ConnectorAccessToken for Payone {} +impl MandateSetup for Payone {} +impl PaymentAuthorize for Payone {} +impl PaymentSync for Payone {} +impl PaymentCapture for Payone {} +impl PaymentVoid for Payone {} +impl Refund for Payone {} +impl RefundExecute for Payone {} +impl RefundSync for Payone {} +impl PaymentToken for Payone {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Payone { } @@ -109,9 +134,9 @@ where #[cfg(feature = "payouts")] fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth = payone::PayoneAuthType::try_from(&req.connector_auth_type)?; let http_method = self.get_http_method().to_string(); let content_type = Self::get_content_type(self); @@ -129,9 +154,9 @@ where date_header.clone(), )?; let headers = vec![ - (headers::DATE.to_string(), date_header.to_string().into()), + (DATE.to_string(), date_header.to_string().into()), ( - headers::AUTHORIZATION.to_string(), + AUTHORIZATION.to_string(), authorization_header.to_string().into(), ), ]; @@ -145,26 +170,26 @@ impl ConnectorCommon for Payone { "payone" } - fn get_currency_unit(&self) -> api::CurrencyUnit { - api::CurrencyUnit::Minor + fn get_currency_unit(&self) -> CurrencyUnit { + CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.payone.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth = payone::PayoneAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(vec![( - headers::AUTHORIZATION.to_string(), + AUTHORIZATION.to_string(), auth.api_key.expose().into_masked(), )]) } @@ -173,34 +198,33 @@ impl ConnectorCommon for Payone { &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: payone::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let errors_list = response.errors.clone().unwrap_or_default(); - let option_error_code_message = - connector_utils::get_error_code_error_message_based_on_priority( - self.clone(), - errors_list - .into_iter() - .map(|errors| errors.into()) - .collect(), - ); + let option_error_code_message = get_error_code_error_message_based_on_priority( + self.clone(), + errors_list + .into_iter() + .map(|errors| errors.into()) + .collect(), + ); match response.errors { Some(errors) => Ok(ErrorResponse { status_code: res.status_code, code: option_error_code_message .clone() .map(|error_code_message| error_code_message.error_code) - .unwrap_or(consts::NO_ERROR_CODE.to_string()), + .unwrap_or(NO_ERROR_CODE.to_string()), message: option_error_code_message .clone() .map(|error_code_message| error_code_message.error_code) - .unwrap_or(consts::NO_ERROR_CODE.to_string()), + .unwrap_or(NO_ERROR_CODE.to_string()), reason: Some( errors .iter() @@ -216,8 +240,8 @@ impl ConnectorCommon for Payone { }), None => Ok(ErrorResponse { status_code: res.status_code, - code: consts::NO_ERROR_CODE.to_string(), - message: consts::NO_ERROR_MESSAGE.to_string(), + code: NO_ERROR_CODE.to_string(), + message: NO_ERROR_MESSAGE.to_string(), reason: None, attempt_status: None, connector_transaction_id: None, @@ -230,64 +254,38 @@ impl ConnectorCommon for Payone { } impl ConnectorValidation for Payone {} -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Payone -{ -} +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Payone {} -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Payone -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Payone {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Payone -{ -} +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Payone {} -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Payone -{ -} +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Payone {} -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Payone -{ -} +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Payone {} -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Payone -{ -} +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Payone {} -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Payone -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Payone {} -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Payone {} +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Payone {} -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Payone {} -impl api::Payouts for Payone {} +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Payone {} +#[cfg(feature = "payouts")] +impl Payouts for Payone {} #[cfg(feature = "payouts")] -impl api::PayoutFulfill for Payone {} +impl PayoutFulfill for Payone {} #[cfg(feature = "payouts")] -impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> - for Payone -{ +impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Payone { fn get_url( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - _connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + _connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { let auth = payone::PayoneAuthType::try_from(&req.connector_auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(format!( "{}v2/{}/payouts", self.base_url(_connectors), @@ -297,17 +295,17 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, @@ -320,19 +318,15 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp fn build_request( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutFulfillType::get_headers( - self, req, connectors, - )?) - .set_body(types::PayoutFulfillType::get_request_body( - self, req, connectors, - )?) + .headers(PayoutFulfillType::get_headers(self, req, connectors)?) + .set_body(PayoutFulfillType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } @@ -340,19 +334,19 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp #[instrument(skip_all)] fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoFulfill>, + data: &PayoutsRouterData<PoFulfill>, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { + ) -> CustomResult<PayoutsRouterData<PoFulfill>, ConnectorError> { let response: payone::PayonePayoutFulfillResponse = res .response .parse_struct("PayonePayoutFulfillResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -363,32 +357,32 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] -impl api::IncomingWebhook for Payone { +impl IncomingWebhook for Payone { fn get_webhook_object_reference_id( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) } } diff --git a/crates/router/src/connector/payone/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payone/transformers.rs similarity index 61% rename from crates/router/src/connector/payone/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/payone/transformers.rs index 2ac9c083018..8beae986e3a 100644 --- a/crates/router/src/connector/payone/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payone/transformers.rs @@ -2,31 +2,36 @@ use api_models::payouts::PayoutMethodData; #[cfg(feature = "payouts")] use cards::CardNumber; +#[cfg(feature = "payouts")] +use common_enums::{PayoutStatus, PayoutType}; use common_utils::types::MinorUnit; #[cfg(feature = "payouts")] +use common_utils::{ext_traits::OptionExt, transformers::ForeignFrom}; +#[cfg(feature = "payouts")] use error_stack::ResultExt; +use hyperswitch_domain_models::router_data::ConnectorAuthType; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::PoFulfill, + types::{PayoutsResponseData, PayoutsRouterData}, +}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::{Deserialize, Serialize}; -use serde_repr::{Deserialize_repr, Serialize_repr}; - -use crate::connector::{ - utils, - utils::{get_unimplemented_payment_method_error_message, CardIssuer}, -}; #[cfg(feature = "payouts")] -type Error = error_stack::Report<errors::ConnectorError>; - +use crate::utils::CardData as _; +use crate::utils::{ + get_unimplemented_payment_method_error_message, CardIssuer, ErrorCodeAndMessage, +}; #[cfg(feature = "payouts")] use crate::{ - connector::utils::{CardData, PayoutsData, RouterData}, - core::errors, - types::{self, api, storage::enums as storage_enums, transformers::ForeignFrom}, - utils::OptionExt, + types::PayoutsResponseRouterData, + utils::{PayoutsData, RouterData}, }; -#[cfg(not(feature = "payouts"))] -use crate::{core::errors, types}; - +#[cfg(feature = "payouts")] +type Error = error_stack::Report<ConnectorError>; +use serde_repr::{Deserialize_repr, Serialize_repr}; pub struct PayoneRouterData<T> { pub amount: MinorUnit, pub router_data: T, @@ -54,7 +59,7 @@ pub struct SubError { pub http_status_code: u16, } -impl From<SubError> for utils::ErrorCodeAndMessage { +impl From<SubError> for ErrorCodeAndMessage { fn from(error: SubError) -> Self { Self { error_code: error.code.to_string(), @@ -69,11 +74,11 @@ pub struct PayoneAuthType { pub api_secret: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for PayoneAuthType { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { +impl TryFrom<&ConnectorAuthType> for PayoneAuthType { + type Error = error_stack::Report<ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::SignatureKey { + ConnectorAuthType::SignatureKey { api_key, key1, api_secret, @@ -82,7 +87,7 @@ impl TryFrom<&types::ConnectorAuthType> for PayoneAuthType { merchant_account: key1.to_owned(), api_secret: api_secret.to_owned(), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, + _ => Err(ConnectorError::FailedToObtainAuthType)?, } } } @@ -121,60 +126,54 @@ pub struct Card { } #[cfg(feature = "payouts")] -impl TryFrom<PayoneRouterData<&types::PayoutsRouterData<api::PoFulfill>>> - for PayonePayoutFulfillRequest -{ +impl TryFrom<PayoneRouterData<&PayoutsRouterData<PoFulfill>>> for PayonePayoutFulfillRequest { type Error = Error; fn try_from( - item: PayoneRouterData<&types::PayoutsRouterData<api::PoFulfill>>, + item: PayoneRouterData<&PayoutsRouterData<PoFulfill>>, ) -> Result<Self, Self::Error> { let request = item.router_data.request.to_owned(); let payout_type = request.get_payout_type()?; match payout_type { - storage_enums::PayoutType::Card => { + PayoutType::Card => { let amount_of_money: AmountOfMoney = AmountOfMoney { amount: item.amount, currency_code: item.router_data.request.destination_currency.to_string(), }; - let card_payout_method_specific_input = match item - .router_data - .get_payout_method_data()? - { - PayoutMethodData::Card(card_data) => CardPayoutMethodSpecificInput { - card: Card { - card_number: card_data.card_number.clone(), - card_holder_name: card_data - .card_holder_name - .clone() - .get_required_value("card_holder_name") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "payout_method_data.card.holder_name", - })?, - expiry_date: card_data - .get_card_expiry_month_year_2_digit_with_delimiter( - "".to_string(), - )?, + let card_payout_method_specific_input = + match item.router_data.get_payout_method_data()? { + PayoutMethodData::Card(card_data) => CardPayoutMethodSpecificInput { + card: Card { + card_number: card_data.card_number.clone(), + card_holder_name: card_data + .card_holder_name + .clone() + .get_required_value("card_holder_name") + .change_context(ConnectorError::MissingRequiredField { + field_name: "payout_method_data.card.holder_name", + })?, + expiry_date: card_data + .get_card_expiry_month_year_2_digit_with_delimiter( + "".to_string(), + )?, + }, + payment_product_id: PaymentProductId::try_from( + card_data.get_card_issuer()?, + )?, }, - payment_product_id: PaymentProductId::try_from( - card_data.get_card_issuer()?, - )?, - }, - PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => { - Err(errors::ConnectorError::NotImplemented( - get_unimplemented_payment_method_error_message("Payone"), - ))? - } - }; + PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => { + Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Payone"), + ))? + } + }; Ok(Self { amount_of_money, card_payout_method_specific_input, }) } - storage_enums::PayoutType::Wallet | storage_enums::PayoutType::Bank => { - Err(errors::ConnectorError::NotImplemented( - get_unimplemented_payment_method_error_message("Payone"), - ))? - } + PayoutType::Wallet | PayoutType::Bank => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Payone"), + ))?, } } } @@ -187,7 +186,7 @@ pub enum PaymentProductId { } impl TryFrom<CardIssuer> for PaymentProductId { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from(issuer: CardIssuer) -> Result<Self, Self::Error> { match issuer { CardIssuer::Master => Ok(Self::MasterCard), @@ -197,7 +196,7 @@ impl TryFrom<CardIssuer> for PaymentProductId { | CardIssuer::Discover | CardIssuer::DinersClub | CardIssuer::JCB - | CardIssuer::CarteBlanche => Err(errors::ConnectorError::NotImplemented( + | CardIssuer::CarteBlanche => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("payone"), ) .into()), @@ -237,7 +236,7 @@ pub struct PayoutOutput { } #[cfg(feature = "payouts")] -impl ForeignFrom<PayoneStatus> for storage_enums::PayoutStatus { +impl ForeignFrom<PayoneStatus> for PayoutStatus { fn foreign_from(payone_status: PayoneStatus) -> Self { match payone_status { PayoneStatus::AccountCredited => Self::Success, @@ -251,18 +250,18 @@ impl ForeignFrom<PayoneStatus> for storage_enums::PayoutStatus { } #[cfg(feature = "payouts")] -impl<F> TryFrom<types::PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>> - for types::PayoutsRouterData<F> +impl<F> TryFrom<PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>> + for PayoutsRouterData<F> { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>, + item: PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>, ) -> Result<Self, Self::Error> { let response: PayonePayoutFulfillResponse = item.response; Ok(Self { - response: Ok(types::PayoutsResponseData { - status: Some(storage_enums::PayoutStatus::foreign_from(response.status)), + response: Ok(PayoutsResponseData { + status: Some(PayoutStatus::foreign_from(response.status)), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, diff --git a/crates/router/src/connector/riskified.rs b/crates/hyperswitch_connectors/src/connectors/riskified.rs similarity index 51% rename from crates/router/src/connector/riskified.rs rename to crates/hyperswitch_connectors/src/connectors/riskified.rs index 971bd5de04f..269ac0700c4 100644 --- a/crates/router/src/connector/riskified.rs +++ b/crates/hyperswitch_connectors/src/connectors/riskified.rs @@ -1,51 +1,96 @@ pub mod transformers; - +#[cfg(feature = "frm")] +use api_models::webhooks::{ConnectorWebhookSecrets, IncomingWebhookEvent, ObjectReferenceId}; #[cfg(feature = "frm")] use base64::Engine; -use common_utils::types::{ - AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector, +#[cfg(feature = "frm")] +use common_utils::types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}; +#[cfg(feature = "frm")] +use common_utils::{ + consts::BASE64_ENGINE, + request::{Method, RequestBuilder}, + types::MinorUnit, }; #[cfg(feature = "frm")] use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; +use common_utils::{errors::CustomResult, request::Request}; #[cfg(feature = "frm")] use error_stack::ResultExt; #[cfg(feature = "frm")] -use masking::{ExposeInterface, PeekInterface, Secret}; +use hyperswitch_domain_models::{ + router_data::ErrorResponse, + router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, + router_request_types::fraud_check::{ + FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, + FraudCheckSaleData, FraudCheckTransactionData, + }, + router_response_types::fraud_check::FraudCheckResponseData, +}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, RouterData}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, +}; +use hyperswitch_interfaces::{ + api::{ + ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, + ConnectorSpecifications, ConnectorValidation, MandateSetup, Payment, PaymentAuthorize, + PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, Refund, + RefundExecute, RefundSync, + }, + configs::Connectors, + errors::ConnectorError, +}; +#[cfg(feature = "frm")] +use hyperswitch_interfaces::{ + api::{ + FraudCheck, FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, + FraudCheckSale, FraudCheckTransaction, + }, + events::connector_api_logs::ConnectorEvent, + types::Response, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +#[cfg(feature = "frm")] +use masking::Maskable; +#[cfg(feature = "frm")] +use masking::{ExposeInterface, Mask, PeekInterface, Secret}; #[cfg(feature = "frm")] use ring::hmac; #[cfg(feature = "frm")] use transformers as riskified; -use super::utils::convert_amount; #[cfg(feature = "frm")] -use super::utils::{self as connector_utils, FrmTransactionRouterDataRequest}; +use crate::constants::headers; +#[cfg(feature = "frm")] +use crate::utils::convert_amount; +#[cfg(feature = "frm")] use crate::{ - configs::settings, - core::errors::{self, CustomResult}, - services::{self, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, + FrmCheckoutRouterData, FrmCheckoutType, FrmFulfillmentRouterData, FrmFulfillmentType, + FrmTransactionRouterData, FrmTransactionType, ResponseRouterData, }, -}; -#[cfg(feature = "frm")] -use crate::{ - consts, - events::connector_api_logs::ConnectorEvent, - headers, - services::request, - types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, - utils::BytesExt, + utils::FrmTransactionRouterDataRequest, }; #[derive(Clone)] pub struct Riskified { + #[cfg(feature = "frm")] amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Riskified { pub fn new() -> &'static Self { &Self { + #[cfg(feature = "frm")] amount_converter: &StringMajorUnitForConnector, } } @@ -55,7 +100,7 @@ impl Riskified { &self, auth: &riskified::RiskifiedAuthType, payload: &str, - ) -> CustomResult<String, errors::ConnectorError> { + ) -> CustomResult<String, ConnectorError> { let key = hmac::Key::new( hmac::HMAC_SHA256, auth.secret_token.clone().expose().as_bytes(), @@ -76,9 +121,9 @@ where #[cfg(feature = "frm")] fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth: riskified::RiskifiedAuthType = riskified::RiskifiedAuthType::try_from(&req.connector_auth_type)?; @@ -89,7 +134,7 @@ where let digest = self .generate_authorization_signature(&auth, payload) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + .change_context(ConnectorError::RequestEncodingFailed)?; let header = vec![ ( @@ -102,7 +147,7 @@ where ), ( "X-RISKIFIED-HMAC-SHA256".to_string(), - request::Mask::into_masked(digest), + Mask::into_masked(digest), ), ( "Accept".to_string(), @@ -122,7 +167,7 @@ impl ConnectorCommon for Riskified { fn common_get_content_type(&self) -> &'static str { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.riskified.base_url.as_ref() } @@ -131,11 +176,13 @@ impl ConnectorCommon for Riskified { &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { + use hyperswitch_interfaces::consts::NO_ERROR_CODE; + let response: riskified::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -143,7 +190,7 @@ impl ConnectorCommon for Riskified { Ok(ErrorResponse { status_code: res.status_code, attempt_status: None, - code: consts::NO_ERROR_CODE.to_string(), + code: NO_ERROR_CODE.to_string(), message: response.error.message.clone(), reason: None, connector_transaction_id: None, @@ -155,18 +202,12 @@ impl ConnectorCommon for Riskified { } #[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::Checkout, - frm_types::FraudCheckCheckoutData, - frm_types::FraudCheckResponseData, - > for Riskified -{ +impl ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> for Riskified { fn get_headers( &self, - req: &frm_types::FrmCheckoutRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &FrmCheckoutRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -176,23 +217,23 @@ impl fn get_url( &self, - _req: &frm_types::FrmCheckoutRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &FrmCheckoutRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "/decide")) } fn get_request_body( &self, - req: &frm_types::FrmCheckoutRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &FrmCheckoutRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let amount = convert_amount( self.amount_converter, MinorUnit::new(req.request.amount), req.request .currency - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "currency", })?, )?; @@ -203,37 +244,33 @@ impl fn build_request( &self, - req: &frm_types::FrmCheckoutRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &FrmCheckoutRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&frm_types::FrmCheckoutType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Post) + .url(&FrmCheckoutType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(frm_types::FrmCheckoutType::get_headers( - self, req, connectors, - )?) - .set_body(frm_types::FrmCheckoutType::get_request_body( - self, req, connectors, - )?) + .headers(FrmCheckoutType::get_headers(self, req, connectors)?) + .set_body(FrmCheckoutType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &frm_types::FrmCheckoutRouterData, + data: &FrmCheckoutRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<frm_types::FrmCheckoutRouterData, errors::ConnectorError> { + ) -> CustomResult<FrmCheckoutRouterData, ConnectorError> { let response: riskified::RiskifiedPaymentsResponse = res .response .parse_struct("RiskifiedPaymentsResponse Checkout") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - <frm_types::FrmCheckoutRouterData>::try_from(types::ResponseRouterData { + <FrmCheckoutRouterData>::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -243,47 +280,36 @@ impl &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl api::Payment for Riskified {} -impl api::PaymentAuthorize for Riskified {} -impl api::PaymentSync for Riskified {} -impl api::PaymentVoid for Riskified {} -impl api::PaymentCapture for Riskified {} -impl api::MandateSetup for Riskified {} -impl api::ConnectorAccessToken for Riskified {} -impl api::PaymentToken for Riskified {} -impl api::Refund for Riskified {} -impl api::RefundExecute for Riskified {} -impl api::RefundSync for Riskified {} +impl Payment for Riskified {} +impl PaymentAuthorize for Riskified {} +impl PaymentSync for Riskified {} +impl PaymentVoid for Riskified {} +impl PaymentCapture for Riskified {} +impl MandateSetup for Riskified {} +impl ConnectorAccessToken for Riskified {} +impl PaymentToken for Riskified {} +impl Refund for Riskified {} +impl RefundExecute for Riskified {} +impl RefundSync for Riskified {} impl ConnectorValidation for Riskified {} #[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::Sale, - frm_types::FraudCheckSaleData, - frm_types::FraudCheckResponseData, - > for Riskified -{ -} +impl ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> for Riskified {} #[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::Transaction, - frm_types::FraudCheckTransactionData, - frm_types::FraudCheckResponseData, - > for Riskified +impl ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData> + for Riskified { fn get_headers( &self, - req: &frm_types::FrmTransactionRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &FrmTransactionRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -293,9 +319,9 @@ impl fn get_url( &self, - req: &frm_types::FrmTransactionRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &FrmTransactionRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { match req.is_payment_successful() { Some(false) => Ok(format!( "{}{}", @@ -308,9 +334,9 @@ impl fn get_request_body( &self, - req: &frm_types::FrmTransactionRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &FrmTransactionRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { match req.is_payment_successful() { Some(false) => { let req_obj = riskified::TransactionFailedRequest::try_from(req)?; @@ -322,7 +348,7 @@ impl MinorUnit::new(req.request.amount), req.request .currency - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "currency", })?, )?; @@ -335,50 +361,44 @@ impl fn build_request( &self, - req: &frm_types::FrmTransactionRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &FrmTransactionRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&frm_types::FrmTransactionType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&FrmTransactionType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(frm_types::FrmTransactionType::get_headers( - self, req, connectors, - )?) - .set_body(frm_types::FrmTransactionType::get_request_body( - self, req, connectors, - )?) + .headers(FrmTransactionType::get_headers(self, req, connectors)?) + .set_body(FrmTransactionType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &frm_types::FrmTransactionRouterData, + data: &FrmTransactionRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<frm_types::FrmTransactionRouterData, errors::ConnectorError> { + ) -> CustomResult<FrmTransactionRouterData, ConnectorError> { let response: riskified::RiskifiedTransactionResponse = res .response .parse_struct("RiskifiedPaymentsResponse Transaction") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); match response { riskified::RiskifiedTransactionResponse::FailedResponse(response_data) => { - <frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData { + <FrmTransactionRouterData>::try_from(ResponseRouterData { response: response_data, data: data.clone(), http_code: res.status_code, }) } riskified::RiskifiedTransactionResponse::SuccessResponse(response_data) => { - <frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData { + <FrmTransactionRouterData>::try_from(ResponseRouterData { response: response_data, data: data.clone(), http_code: res.status_code, @@ -390,24 +410,20 @@ impl &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::Fulfillment, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, - > for Riskified +impl ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> + for Riskified { fn get_headers( &self, - req: &frm_types::FrmFulfillmentRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &FrmFulfillmentRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -417,58 +433,52 @@ impl fn get_url( &self, - _req: &frm_types::FrmFulfillmentRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &FrmFulfillmentRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "/fulfill")) } fn get_request_body( &self, - req: &frm_types::FrmFulfillmentRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &FrmFulfillmentRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let req_obj = riskified::RiskifiedFulfillmentRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, - req: &frm_types::FrmFulfillmentRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &FrmFulfillmentRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&frm_types::FrmFulfillmentType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&FrmFulfillmentType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(frm_types::FrmFulfillmentType::get_headers( - self, req, connectors, - )?) - .set_body(frm_types::FrmFulfillmentType::get_request_body( - self, req, connectors, - )?) + .headers(FrmFulfillmentType::get_headers(self, req, connectors)?) + .set_body(FrmFulfillmentType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &frm_types::FrmFulfillmentRouterData, + data: &FrmFulfillmentRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> { + ) -> CustomResult<FrmFulfillmentRouterData, ConnectorError> { let response: riskified::RiskifiedFulfilmentResponse = res .response .parse_struct("RiskifiedFulfilmentResponse fulfilment") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - frm_types::FrmFulfillmentRouterData::try_from(types::ResponseRouterData { + FrmFulfillmentRouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -479,136 +489,93 @@ impl &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::RecordReturn, - frm_types::FraudCheckRecordReturnData, - frm_types::FraudCheckResponseData, - > for Riskified -{ -} - -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Riskified +impl ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData> + for Riskified { } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Riskified { } -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Riskified +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Riskified {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Riskified { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Err( - errors::ConnectorError::NotImplemented("Setup Mandate flow for Riskified".to_string()) - .into(), - ) + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Err(ConnectorError::NotImplemented("Setup Mandate flow for Riskified".to_string()).into()) } } -impl api::PaymentSession for Riskified {} +impl PaymentSession for Riskified {} -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Riskified {} -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Riskified {} -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Riskified {} -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Riskified {} -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Riskified {} -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Riskified {} -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Riskified -{ -} +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Riskified {} #[cfg(feature = "frm")] -impl api::FraudCheck for Riskified {} +impl FraudCheck for Riskified {} #[cfg(feature = "frm")] -impl frm_api::FraudCheckSale for Riskified {} +impl FraudCheckSale for Riskified {} #[cfg(feature = "frm")] -impl frm_api::FraudCheckCheckout for Riskified {} +impl FraudCheckCheckout for Riskified {} #[cfg(feature = "frm")] -impl frm_api::FraudCheckTransaction for Riskified {} +impl FraudCheckTransaction for Riskified {} #[cfg(feature = "frm")] -impl frm_api::FraudCheckFulfillment for Riskified {} +impl FraudCheckFulfillment for Riskified {} #[cfg(feature = "frm")] -impl frm_api::FraudCheckRecordReturn for Riskified {} +impl FraudCheckRecordReturn for Riskified {} #[cfg(feature = "frm")] #[async_trait::async_trait] -impl api::IncomingWebhook for Riskified { +impl IncomingWebhook for Riskified { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + _connector_webhook_secrets: &ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, ConnectorError> { let header_value = - connector_utils::get_header_key_value("x-riskified-hmac-sha256", request.headers)?; + crate::utils::get_header_key_value("x-riskified-hmac-sha256", request.headers)?; Ok(header_value.as_bytes().to_vec()) } async fn verify_webhook_source( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, - ) -> CustomResult<bool, errors::ConnectorError> { + ) -> CustomResult<bool, ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, @@ -616,11 +583,11 @@ impl api::IncomingWebhook for Riskified { connector_webhook_details, ) .await - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let message = self .get_webhook_source_verification_message( @@ -628,55 +595,55 @@ impl api::IncomingWebhook for Riskified { merchant_id, &connector_webhook_secrets, ) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &connector_webhook_secrets.secret); let signed_message = hmac::sign(&signing_key, &message); - let payload_sign = consts::BASE64_ENGINE.encode(signed_message.as_ref()); + let payload_sign = BASE64_ENGINE.encode(signed_message.as_ref()); Ok(payload_sign.as_bytes().eq(&signature)) } fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, - _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + _connector_webhook_secrets: &ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, ConnectorError> { Ok(request.body.to_vec()) } fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, ConnectorError> { let resource: riskified::RiskifiedWebhookBody = request .body .parse_struct("RiskifiedWebhookBody") - .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; - Ok(api::webhooks::ObjectReferenceId::PaymentId( + .change_context(ConnectorError::WebhookReferenceIdNotFound)?; + Ok(ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(resource.id), )) } fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { let resource: riskified::RiskifiedWebhookBody = request .body .parse_struct("RiskifiedWebhookBody") - .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - Ok(api::IncomingWebhookEvent::from(resource.status)) + .change_context(ConnectorError::WebhookEventTypeNotFound)?; + Ok(IncomingWebhookEvent::from(resource.status)) } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { let resource: riskified::RiskifiedWebhookBody = request .body .parse_struct("RiskifiedWebhookBody") - .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + .change_context(ConnectorError::WebhookResourceObjectNotFound)?; Ok(Box::new(resource)) } } diff --git a/crates/router/src/connector/riskified/transformers.rs b/crates/hyperswitch_connectors/src/connectors/riskified/transformers.rs similarity index 100% rename from crates/router/src/connector/riskified/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/riskified/transformers.rs diff --git a/crates/router/src/connector/riskified/transformers/api.rs b/crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs similarity index 82% rename from crates/router/src/connector/riskified/transformers/api.rs rename to crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs index e8c1b874417..7ce3ac979e3 100644 --- a/crates/router/src/connector/riskified/transformers/api.rs +++ b/crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs @@ -1,4 +1,5 @@ -use api_models::payments::AdditionalPaymentData; +use api_models::{payments::AdditionalPaymentData, webhooks::IncomingWebhookEvent}; +use common_enums::{Currency, FraudCheckStatus}; use common_utils::{ ext_traits::ValueExt, id_type, @@ -6,26 +7,32 @@ use common_utils::{ types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{self, ResultExt}; +use hyperswitch_domain_models::{ + router_data::RouterData, + router_flow_types::Fulfillment, + router_request_types::{ + fraud_check::{FraudCheckFulfillmentData, FulfillmentStatus}, + BrowserInformation, ResponseId, + }, + router_response_types::fraud_check::FraudCheckResponseData, +}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ - connector::utils::{ - convert_amount, AddressDetailsData, FraudCheckCheckoutRequest, - FraudCheckTransactionRequest, RouterData, - }, - core::{errors, fraud_check::types as core_types}, types::{ - self, - api::{self, Fulfillment}, - fraud_check as frm_types, - storage::enums as storage_enums, - ResponseId, ResponseRouterData, + FrmCheckoutRouterData, FrmFulfillmentRouterData, FrmTransactionRouterData, + ResponseRouterData, + }, + utils::{ + convert_amount, AddressDetailsData as _, FraudCheckCheckoutRequest, + FraudCheckTransactionRequest, RouterData as _, }, }; -type Error = error_stack::Report<errors::ConnectorError>; +type Error = error_stack::Report<ConnectorError>; pub struct RiskifiedRouterData<T> { pub amount: StringMajorUnit, @@ -55,7 +62,7 @@ pub struct CheckoutRequest { email: Option<Email>, #[serde(with = "common_utils::custom_serde::iso8601")] created_at: PrimitiveDateTime, - currency: Option<common_enums::Currency>, + currency: Option<Currency>, #[serde(with = "common_utils::custom_serde::iso8601")] updated_at: PrimitiveDateTime, gateway: Option<String>, @@ -157,22 +164,20 @@ pub struct RiskifiedMetadata { shipping_lines: Vec<ShippingLines>, } -impl TryFrom<&RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>> - for RiskifiedPaymentsCheckoutRequest -{ +impl TryFrom<&RiskifiedRouterData<&FrmCheckoutRouterData>> for RiskifiedPaymentsCheckoutRequest { type Error = Error; fn try_from( - payment: &RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>, + payment: &RiskifiedRouterData<&FrmCheckoutRouterData>, ) -> Result<Self, Self::Error> { let payment_data = payment.router_data.clone(); let metadata: RiskifiedMetadata = payment_data .frm_metadata .clone() - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "frm_metadata", })? .parse_value("Riskified Metadata") - .change_context(errors::ConnectorError::InvalidDataFormat { + .change_context(ConnectorError::InvalidDataFormat { field_name: "frm_metadata", })?; let billing_address = payment_data.get_billing()?; @@ -187,7 +192,7 @@ impl TryFrom<&RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>> payment.amount_converter, order_detail.amount, payment_data.request.currency.ok_or_else(|| { - errors::ConnectorError::MissingRequiredField { + ConnectorError::MissingRequiredField { field_name: "currency", } })?, @@ -251,7 +256,7 @@ impl TryFrom<&RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>> .as_ref() .and_then(|browser_info| browser_info.user_agent.clone()), accept_language: payment_data.request.browser_info.as_ref().and_then( - |browser_info: &types::BrowserInformation| browser_info.language.clone(), + |browser_info: &BrowserInformation| browser_info.language.clone(), ), }, note: payment_data.description.clone(), @@ -312,23 +317,17 @@ pub enum PaymentStatus { Processing, } -impl<F, T> - TryFrom<ResponseRouterData<F, RiskifiedPaymentsResponse, T, frm_types::FraudCheckResponseData>> - for types::RouterData<F, T, frm_types::FraudCheckResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, RiskifiedPaymentsResponse, T, FraudCheckResponseData>> + for RouterData<F, T, FraudCheckResponseData> { type Error = Error; fn try_from( - item: ResponseRouterData< - F, - RiskifiedPaymentsResponse, - T, - frm_types::FraudCheckResponseData, - >, + item: ResponseRouterData<F, RiskifiedPaymentsResponse, T, FraudCheckResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(frm_types::FraudCheckResponseData::TransactionResponse { + response: Ok(FraudCheckResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order.id), - status: storage_enums::FraudCheckStatus::from(item.response.order.status), + status: FraudCheckStatus::from(item.response.order.status), connector_metadata: None, score: None, reason: item.response.order.description.map(serde_json::Value::from), @@ -338,7 +337,7 @@ impl<F, T> } } -impl From<PaymentStatus> for storage_enums::FraudCheckStatus { +impl From<PaymentStatus> for FraudCheckStatus { fn from(item: PaymentStatus) -> Self { match item { PaymentStatus::Approved => Self::Legit, @@ -372,9 +371,9 @@ pub struct AuthorizationError { message: Option<String>, } -impl TryFrom<&frm_types::FrmTransactionRouterData> for TransactionFailedRequest { +impl TryFrom<&FrmTransactionRouterData> for TransactionFailedRequest { type Error = Error; - fn try_from(item: &frm_types::FrmTransactionRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &FrmTransactionRouterData) -> Result<Self, Self::Error> { Ok(Self { checkout: FailedTransactionData { id: item.attempt_id.clone(), @@ -404,28 +403,17 @@ pub enum RiskifiedTransactionResponse { } impl<F, T> - TryFrom< - ResponseRouterData< - F, - RiskifiedFailedTransactionResponse, - T, - frm_types::FraudCheckResponseData, - >, - > for types::RouterData<F, T, frm_types::FraudCheckResponseData> + TryFrom<ResponseRouterData<F, RiskifiedFailedTransactionResponse, T, FraudCheckResponseData>> + for RouterData<F, T, FraudCheckResponseData> { type Error = Error; fn try_from( - item: ResponseRouterData< - F, - RiskifiedFailedTransactionResponse, - T, - frm_types::FraudCheckResponseData, - >, + item: ResponseRouterData<F, RiskifiedFailedTransactionResponse, T, FraudCheckResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(frm_types::FraudCheckResponseData::TransactionResponse { + response: Ok(FraudCheckResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.checkout.id), - status: storage_enums::FraudCheckStatus::from(item.response.checkout.status), + status: FraudCheckStatus::from(item.response.checkout.status), connector_metadata: None, score: None, reason: item @@ -455,7 +443,7 @@ pub struct TransactionDecisionData { external_status: TransactionStatus, reason: Option<String>, amount: StringMajorUnit, - currency: storage_enums::Currency, + currency: Currency, #[serde(with = "common_utils::custom_serde::iso8601")] decided_at: PrimitiveDateTime, payment_details: Vec<TransactionPaymentDetails>, @@ -472,12 +460,10 @@ pub enum TransactionStatus { Approved, } -impl TryFrom<&RiskifiedRouterData<&frm_types::FrmTransactionRouterData>> - for TransactionSuccessRequest -{ +impl TryFrom<&RiskifiedRouterData<&FrmTransactionRouterData>> for TransactionSuccessRequest { type Error = Error; fn try_from( - item_data: &RiskifiedRouterData<&frm_types::FrmTransactionRouterData>, + item_data: &RiskifiedRouterData<&FrmTransactionRouterData>, ) -> Result<Self, Self::Error> { let item = item_data.router_data.clone(); Ok(Self { @@ -530,16 +516,16 @@ pub struct FulfilmentData { tracking_url: Option<String>, } -impl TryFrom<&frm_types::FrmFulfillmentRouterData> for RiskifiedFulfillmentRequest { +impl TryFrom<&FrmFulfillmentRouterData> for RiskifiedFulfillmentRequest { type Error = Error; - fn try_from(item: &frm_types::FrmFulfillmentRouterData) -> Result<Self, Self::Error> { + fn try_from(item: &FrmFulfillmentRouterData) -> Result<Self, Self::Error> { let tracking_number = item .request .fulfillment_req .tracking_numbers .as_ref() .and_then(|numbers| numbers.first().cloned()) - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "tracking_number", })?; let tracking_url = item @@ -565,7 +551,7 @@ impl TryFrom<&frm_types::FrmFulfillmentRouterData> for RiskifiedFulfillmentReque .fulfillment_req .tracking_company .clone() - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "tracking_company", })?, tracking_number, @@ -581,27 +567,22 @@ impl ResponseRouterData< Fulfillment, RiskifiedFulfilmentResponse, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, + FraudCheckFulfillmentData, + FraudCheckResponseData, >, - > - for types::RouterData< - Fulfillment, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, - > + > for RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> { type Error = Error; fn try_from( item: ResponseRouterData< Fulfillment, RiskifiedFulfilmentResponse, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, + FraudCheckFulfillmentData, + FraudCheckResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(frm_types::FraudCheckResponseData::FulfillmentResponse { + response: Ok(FraudCheckResponseData::FulfillmentResponse { order_id: item.response.order.id, shipment_ids: Vec::new(), }), @@ -625,13 +606,12 @@ impl TryFrom<&hyperswitch_domain_models::address::Address> for OrderAddress { fn try_from( address_info: &hyperswitch_domain_models::address::Address, ) -> Result<Self, Self::Error> { - let address = - address_info - .clone() - .address - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "address", - })?; + let address = address_info + .clone() + .address + .ok_or(ConnectorError::MissingRequiredField { + field_name: "address", + })?; Ok(Self { first_name: address.first_name.clone(), last_name: address.last_name.clone(), @@ -648,13 +628,11 @@ impl TryFrom<&hyperswitch_domain_models::address::Address> for OrderAddress { } } -fn get_fulfillment_status( - status: core_types::FulfillmentStatus, -) -> Option<FulfillmentRequestStatus> { +fn get_fulfillment_status(status: FulfillmentStatus) -> Option<FulfillmentRequestStatus> { match status { - core_types::FulfillmentStatus::COMPLETE => Some(FulfillmentRequestStatus::Success), - core_types::FulfillmentStatus::CANCELED => Some(FulfillmentRequestStatus::Cancelled), - core_types::FulfillmentStatus::PARTIAL | core_types::FulfillmentStatus::REPLACEMENT => None, + FulfillmentStatus::COMPLETE => Some(FulfillmentRequestStatus::Success), + FulfillmentStatus::CANCELED => Some(FulfillmentRequestStatus::Cancelled), + FulfillmentStatus::PARTIAL | FulfillmentStatus::REPLACEMENT => None, } } @@ -670,7 +648,7 @@ pub enum RiskifiedWebhookStatus { Declined, } -impl From<RiskifiedWebhookStatus> for api::IncomingWebhookEvent { +impl From<RiskifiedWebhookStatus> for IncomingWebhookEvent { fn from(value: RiskifiedWebhookStatus) -> Self { match value { RiskifiedWebhookStatus::Declined => Self::FrmRejected, diff --git a/crates/hyperswitch_connectors/src/connectors/riskified/transformers/auth.rs b/crates/hyperswitch_connectors/src/connectors/riskified/transformers/auth.rs new file mode 100644 index 00000000000..2835ea01f8d --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/riskified/transformers/auth.rs @@ -0,0 +1,22 @@ +use error_stack; +use hyperswitch_domain_models::router_data::ConnectorAuthType; +use hyperswitch_interfaces::errors::ConnectorError; +use masking::{ExposeInterface, Secret}; + +pub struct RiskifiedAuthType { + pub secret_token: Secret<String>, + pub domain_name: String, +} + +impl TryFrom<&ConnectorAuthType> for RiskifiedAuthType { + type Error = error_stack::Report<ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + secret_token: api_key.to_owned(), + domain_name: key1.to_owned().expose(), + }), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), + } + } +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index c21c1d716b1..3acb8c54e27 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -158,6 +158,7 @@ default_imp_for_authorize_session_token!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -168,6 +169,7 @@ default_imp_for_authorize_session_token!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -182,6 +184,7 @@ default_imp_for_authorize_session_token!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Stripebilling, @@ -266,12 +269,14 @@ default_imp_for_calculate_tax!( connectors::Opayo, connectors::Opennode, connectors::Paybox, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, connectors::Nuvei, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -282,6 +287,7 @@ default_imp_for_calculate_tax!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -355,6 +361,7 @@ default_imp_for_session_update!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -364,6 +371,7 @@ default_imp_for_session_update!( connectors::Mollie, connectors::Moneris, connectors::Multisafepay, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -375,6 +383,7 @@ default_imp_for_session_update!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paystack, connectors::Payu, connectors::Placetopay, @@ -455,6 +464,7 @@ default_imp_for_post_session_tokens!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Square, connectors::Stax, @@ -464,6 +474,7 @@ default_imp_for_post_session_tokens!( connectors::Mollie, connectors::Moneris, connectors::Multisafepay, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -475,6 +486,7 @@ default_imp_for_post_session_tokens!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paystack, connectors::Payu, connectors::Placetopay, @@ -573,12 +585,14 @@ default_imp_for_update_metadata!( connectors::Opayo, connectors::Opennode, connectors::Nuvei, + connectors::Nmi, connectors::Paybox, connectors::Payeezy, connectors::Payme, connectors::Paystack, connectors::Payu, connectors::Placetopay, + connectors::Payone, connectors::Fiuu, connectors::Globalpay, connectors::Globepay, @@ -590,6 +604,7 @@ default_imp_for_update_metadata!( connectors::Xendit, connectors::Powertranz, connectors::Prophetpay, + connectors::Riskified, connectors::Thunes, connectors::Trustpay, connectors::Tsys, @@ -660,12 +675,14 @@ default_imp_for_complete_authorize!( connectors::Opayo, connectors::Opennode, connectors::Payeezy, + connectors::Payone, connectors::Paystack, connectors::Payu, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, + connectors::Riskified, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -740,6 +757,7 @@ default_imp_for_incremental_authorization!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -751,6 +769,7 @@ default_imp_for_incremental_authorization!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -765,6 +784,7 @@ default_imp_for_incremental_authorization!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -844,6 +864,7 @@ default_imp_for_create_customer!( connectors::Mollie, connectors::Moneris, connectors::Multisafepay, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -855,6 +876,7 @@ default_imp_for_create_customer!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -865,6 +887,7 @@ default_imp_for_create_customer!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Square, connectors::Stripebilling, @@ -944,6 +967,7 @@ default_imp_for_connector_redirect_response!( connectors::Opennode, connectors::Payeezy, connectors::Paystack, + connectors::Payone, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -952,6 +976,7 @@ default_imp_for_connector_redirect_response!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1030,6 +1055,7 @@ default_imp_for_pre_processing_steps!( connectors::Paybox, connectors::Payeezy, connectors::Paystack, + connectors::Payone, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1041,6 +1067,7 @@ default_imp_for_pre_processing_steps!( connectors::Rapyd, connectors::Razorpay, connectors::Recurly, + connectors::Riskified, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -1115,6 +1142,7 @@ default_imp_for_post_processing_steps!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1126,6 +1154,7 @@ default_imp_for_post_processing_steps!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -1140,6 +1169,7 @@ default_imp_for_post_processing_steps!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1224,12 +1254,14 @@ default_imp_for_approve!( connectors::Nexixpay, connectors::Opayo, connectors::Opennode, + connectors::Nmi, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Payone, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -1242,6 +1274,7 @@ default_imp_for_approve!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1319,6 +1352,7 @@ default_imp_for_reject!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1329,6 +1363,7 @@ default_imp_for_reject!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Payone, connectors::Payme, connectors::Paypal, connectors::Paystack, @@ -1344,6 +1379,7 @@ default_imp_for_reject!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1421,6 +1457,7 @@ default_imp_for_webhook_source_verification!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1429,6 +1466,7 @@ default_imp_for_webhook_source_verification!( connectors::Opayo, connectors::Opennode, connectors::Nuvei, + connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payme, @@ -1445,6 +1483,7 @@ default_imp_for_webhook_source_verification!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1521,6 +1560,7 @@ default_imp_for_accept_dispute!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1532,6 +1572,7 @@ default_imp_for_accept_dispute!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -1546,6 +1587,7 @@ default_imp_for_accept_dispute!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1621,6 +1663,7 @@ default_imp_for_submit_evidence!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1633,6 +1676,7 @@ default_imp_for_submit_evidence!( connectors::Payeezy, connectors::Payme, connectors::Paypal, + connectors::Payone, connectors::Paystack, connectors::Payu, connectors::Placetopay, @@ -1646,6 +1690,7 @@ default_imp_for_submit_evidence!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1721,6 +1766,7 @@ default_imp_for_defend_dispute!( connectors::Juspaythreedsserver, connectors::Klarna, connectors::Helcim, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1732,6 +1778,7 @@ default_imp_for_defend_dispute!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -1746,6 +1793,7 @@ default_imp_for_defend_dispute!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1830,6 +1878,7 @@ default_imp_for_file_upload!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -1841,6 +1890,7 @@ default_imp_for_file_upload!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -1855,6 +1905,7 @@ default_imp_for_file_upload!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1932,6 +1983,7 @@ default_imp_for_payouts!( connectors::Opayo, connectors::Opennode, connectors::Paybox, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nuvei, @@ -1946,6 +1998,7 @@ default_imp_for_payouts!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Square, connectors::Stax, @@ -2023,6 +2076,7 @@ default_imp_for_payouts_create!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2033,6 +2087,7 @@ default_imp_for_payouts_create!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paystack, connectors::Payu, connectors::Placetopay, @@ -2046,6 +2101,7 @@ default_imp_for_payouts_create!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2125,6 +2181,7 @@ default_imp_for_payouts_retrieve!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2137,6 +2194,7 @@ default_imp_for_payouts_retrieve!( connectors::Payme, connectors::Paystack, connectors::Payu, + connectors::Payone, connectors::Placetopay, connectors::Powertranz, connectors::Prophetpay, @@ -2148,6 +2206,7 @@ default_imp_for_payouts_retrieve!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2226,6 +2285,7 @@ default_imp_for_payouts_eligibility!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2238,6 +2298,7 @@ default_imp_for_payouts_eligibility!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Payone, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2250,6 +2311,7 @@ default_imp_for_payouts_eligibility!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2333,6 +2395,7 @@ default_imp_for_payouts_fulfill!( connectors::Nexixpay, connectors::Opayo, connectors::Opennode, + connectors::Nmi, connectors::Nuvei, connectors::Paybox, connectors::Payeezy, @@ -2350,6 +2413,7 @@ default_imp_for_payouts_fulfill!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2428,6 +2492,7 @@ default_imp_for_payouts_cancel!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2440,6 +2505,7 @@ default_imp_for_payouts_cancel!( connectors::Payme, connectors::Paypal, connectors::Paystack, + connectors::Payone, connectors::Payu, connectors::Placetopay, connectors::Powertranz, @@ -2452,6 +2518,7 @@ default_imp_for_payouts_cancel!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2531,6 +2598,7 @@ default_imp_for_payouts_quote!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2540,6 +2608,7 @@ default_imp_for_payouts_quote!( connectors::Nuvei, connectors::Paybox, connectors::Payeezy, + connectors::Payone, connectors::Payme, connectors::Paypal, connectors::Paystack, @@ -2555,6 +2624,7 @@ default_imp_for_payouts_quote!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2634,6 +2704,7 @@ default_imp_for_payouts_recipient!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2644,6 +2715,7 @@ default_imp_for_payouts_recipient!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -2658,6 +2730,7 @@ default_imp_for_payouts_recipient!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2737,6 +2810,7 @@ default_imp_for_payouts_recipient_account!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2747,6 +2821,7 @@ default_imp_for_payouts_recipient_account!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -2761,6 +2836,7 @@ default_imp_for_payouts_recipient_account!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2841,6 +2917,7 @@ default_imp_for_frm_sale!( connectors::Juspaythreedsserver, connectors::Klarna, connectors::Nomupay, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -2851,6 +2928,7 @@ default_imp_for_frm_sale!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -2944,6 +3022,7 @@ default_imp_for_frm_checkout!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -2955,6 +3034,7 @@ default_imp_for_frm_checkout!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -3048,6 +3128,7 @@ default_imp_for_frm_transaction!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3059,6 +3140,7 @@ default_imp_for_frm_transaction!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -3152,6 +3234,7 @@ default_imp_for_frm_fulfillment!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3160,6 +3243,7 @@ default_imp_for_frm_fulfillment!( connectors::Opayo, connectors::Opennode, connectors::Nuvei, + connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payme, @@ -3256,6 +3340,7 @@ default_imp_for_frm_record_return!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3267,6 +3352,7 @@ default_imp_for_frm_record_return!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -3355,6 +3441,7 @@ default_imp_for_revoking_mandates!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Novalnet, connectors::Nexinets, @@ -3365,6 +3452,7 @@ default_imp_for_revoking_mandates!( connectors::Paybox, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -3379,6 +3467,7 @@ default_imp_for_revoking_mandates!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -3455,6 +3544,7 @@ default_imp_for_uas_pre_authentication!( connectors::Itaubank, connectors::Jpmorgan, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3465,6 +3555,7 @@ default_imp_for_uas_pre_authentication!( connectors::Nuvei, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -3480,6 +3571,7 @@ default_imp_for_uas_pre_authentication!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -3554,6 +3646,7 @@ default_imp_for_uas_post_authentication!( connectors::Itaubank, connectors::Jpmorgan, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3564,6 +3657,7 @@ default_imp_for_uas_post_authentication!( connectors::Nuvei, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Paystack, connectors::Payu, @@ -3579,6 +3673,7 @@ default_imp_for_uas_post_authentication!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -3654,6 +3749,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Itaubank, connectors::Jpmorgan, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3664,6 +3760,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Nuvei, connectors::Payeezy, connectors::Payme, + connectors::Payone, connectors::Paystack, connectors::Payu, connectors::Powertranz, @@ -3679,6 +3776,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -3746,6 +3844,7 @@ default_imp_for_connector_request_id!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Novalnet, connectors::Noon, @@ -3757,6 +3856,7 @@ default_imp_for_connector_request_id!( connectors::Paystack, connectors::Payu, connectors::Payme, + connectors::Payone, connectors::Paypal, connectors::Powertranz, connectors::Prophetpay, @@ -3770,6 +3870,7 @@ default_imp_for_connector_request_id!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -3841,6 +3942,7 @@ default_imp_for_fraud_check!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Novalnet, connectors::Noon, @@ -3861,6 +3963,7 @@ default_imp_for_fraud_check!( connectors::Opennode, connectors::Paybox, connectors::Payme, + connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, @@ -3967,6 +4070,7 @@ default_imp_for_connector_authentication!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -3978,6 +4082,7 @@ default_imp_for_connector_authentication!( connectors::Payeezy, connectors::Paystack, connectors::Payu, + connectors::Payone, connectors::Powertranz, connectors::Prophetpay, connectors::Mifinity, @@ -3992,6 +4097,7 @@ default_imp_for_connector_authentication!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -4066,6 +4172,7 @@ default_imp_for_uas_authentication!( connectors::Itaubank, connectors::Jpmorgan, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Novalnet, connectors::Nexinets, @@ -4086,11 +4193,13 @@ default_imp_for_uas_authentication!( connectors::Opennode, connectors::Paybox, connectors::Payme, + connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -4159,6 +4268,7 @@ default_imp_for_revenue_recovery! { connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -4179,11 +4289,13 @@ default_imp_for_revenue_recovery! { connectors::Multisafepay, connectors::Paybox, connectors::Payme, + connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -4263,6 +4375,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Jpmorgan, connectors::Klarna, connectors::Nomupay, + connectors::Nmi, connectors::Noon, connectors::Novalnet, connectors::Nexinets, @@ -4282,10 +4395,12 @@ default_imp_for_billing_connector_payment_sync!( connectors::Multisafepay, connectors::Paybox, connectors::Payme, + connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -4362,6 +4477,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Klarna, + connectors::Nmi, connectors::Nomupay, connectors::Noon, connectors::Novalnet, @@ -4382,10 +4498,12 @@ default_imp_for_revenue_recovery_record_back!( connectors::Multisafepay, connectors::Paybox, connectors::Payme, + connectors::Payone, connectors::Placetopay, connectors::Rapyd, connectors::Razorpay, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 41817d955a6..e593cdfc4bf 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -280,6 +280,8 @@ default_imp_for_new_connector_integration_payment!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -300,6 +302,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -383,6 +386,8 @@ default_imp_for_new_connector_integration_refund!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -403,6 +408,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -481,6 +487,8 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -501,6 +509,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -584,6 +593,8 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -604,6 +615,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -686,6 +698,8 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -706,6 +720,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -789,6 +804,8 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -809,6 +826,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -900,6 +918,8 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Nomupay, connectors::Noon, connectors::Novalnet, + connectors::Nmi, + connectors::Payone, connectors::Nexinets, connectors::Nexixpay, connectors::Opayo, @@ -922,6 +942,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1010,6 +1031,8 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Opayo, connectors::Opennode, connectors::Nuvei, + connectors::Nmi, + connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payme, @@ -1027,6 +1050,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1112,6 +1136,8 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1132,6 +1158,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1217,6 +1244,8 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1237,6 +1266,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1322,6 +1352,8 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1342,6 +1374,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1427,6 +1460,8 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1447,6 +1482,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1532,6 +1568,8 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1552,6 +1590,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1637,6 +1676,8 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1657,6 +1698,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1742,6 +1784,8 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1762,6 +1806,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1845,6 +1890,8 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1865,6 +1912,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1950,6 +1998,8 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -1970,6 +2020,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2055,6 +2106,8 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -2075,6 +2128,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2160,6 +2214,8 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -2180,6 +2236,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2265,6 +2322,8 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -2285,6 +2344,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2370,6 +2430,8 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -2390,6 +2452,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2472,6 +2535,8 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -2491,6 +2556,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Razorpay, connectors::Recurly, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2553,6 +2619,8 @@ default_imp_for_new_connector_integration_frm!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payu, @@ -2564,6 +2632,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Rapyd, connectors::Razorpay, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2667,6 +2736,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Rapyd, connectors::Razorpay, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, @@ -2740,6 +2810,8 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, connectors::Paybox, connectors::Payeezy, connectors::Payu, @@ -2751,6 +2823,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Rapyd, connectors::Razorpay, connectors::Redsys, + connectors::Riskified, connectors::Shift4, connectors::Stax, connectors::Square, diff --git a/crates/hyperswitch_connectors/src/types.rs b/crates/hyperswitch_connectors/src/types.rs index 63b857e7ca2..209360d32b7 100644 --- a/crates/hyperswitch_connectors/src/types.rs +++ b/crates/hyperswitch_connectors/src/types.rs @@ -3,20 +3,24 @@ use hyperswitch_domain_models::types::{PayoutsData, PayoutsResponseData}; use hyperswitch_domain_models::{ router_data::{AccessToken, RouterData}, router_flow_types::{ - Accept, AccessTokenAuth, Authorize, Capture, Defend, Evidence, PSync, PreProcessing, - Session, Upload, Void, + Accept, AccessTokenAuth, Authorize, Capture, Checkout, Defend, Evidence, Fulfillment, + PSync, PreProcessing, Session, Transaction, Upload, Void, }, router_request_types::{ + fraud_check::{ + FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckTransactionData, + }, AcceptDisputeRequestData, AccessTokenRequestData, DefendDisputeRequestData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SubmitEvidenceRequestData, UploadFileRequestData, }, router_response_types::{ - AcceptDisputeResponse, DefendDisputeResponse, PaymentsResponseData, RefundsResponseData, - SubmitEvidenceResponse, UploadFileResponse, + fraud_check::FraudCheckResponseData, AcceptDisputeResponse, DefendDisputeResponse, + PaymentsResponseData, RefundsResponseData, SubmitEvidenceResponse, UploadFileResponse, }, }; +use hyperswitch_interfaces::api::ConnectorIntegration; pub(crate) type PaymentsSyncResponseRouterData<R> = ResponseRouterData<PSync, R, PaymentsSyncData, PaymentsResponseData>; @@ -55,3 +59,15 @@ pub struct ResponseRouterData<Flow, R, Request, Response> { pub data: RouterData<Flow, Request, Response>, pub http_code: u16, } +pub type FrmFulfillmentRouterData = + RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>; +pub type FrmCheckoutType = + dyn ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData>; +pub type FrmTransactionType = + dyn ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData>; +pub type FrmTransactionRouterData = + RouterData<Transaction, FraudCheckTransactionData, FraudCheckResponseData>; +pub type FrmFulfillmentType = + dyn ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>; +pub type FrmCheckoutRouterData = + RouterData<Checkout, FraudCheckCheckoutData, FraudCheckResponseData>; diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 60cb878d9a3..e8b88df4fa2 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -38,6 +38,10 @@ use common_utils::{ types::{AmountConvertor, MinorUnit}, }; use error_stack::{report, ResultExt}; +#[cfg(feature = "frm")] +use hyperswitch_domain_models::router_request_types::fraud_check::{ + FraudCheckCheckoutData, FraudCheckTransactionData, +}; use hyperswitch_domain_models::{ address::{Address, AddressDetails, PhoneDetails}, mandates, @@ -69,6 +73,8 @@ use serde_json::Value; use time::PrimitiveDateTime; use unicode_normalization::UnicodeNormalization; +#[cfg(feature = "frm")] +use crate::types::FrmTransactionRouterData; use crate::{constants::UNSUPPORTED_ERROR_MESSAGE, types::RefreshTokenRouterData}; type Error = error_stack::Report<errors::ConnectorError>; @@ -2479,6 +2485,15 @@ macro_rules! capture_method_not_supported { .into()) }; } +#[macro_export] +macro_rules! get_formatted_date_time { + ($date_format:tt) => {{ + let format = time::macros::format_description!($date_format); + time::OffsetDateTime::now_utc() + .format(&format) + .change_context(ConnectorError::InvalidDateFormat) + }}; +} #[macro_export] macro_rules! unimplemented_payment_method { @@ -6073,6 +6088,69 @@ pub fn normalize_string(value: String) -> Result<String, regex::Error> { let normalized = regex.replace_all(&lowercase_value, "").to_string(); Ok(normalized) } +#[cfg(feature = "frm")] +pub trait FrmTransactionRouterDataRequest { + fn is_payment_successful(&self) -> Option<bool>; +} + +#[cfg(feature = "frm")] +impl FrmTransactionRouterDataRequest for FrmTransactionRouterData { + fn is_payment_successful(&self) -> Option<bool> { + match self.status { + AttemptStatus::AuthenticationFailed + | AttemptStatus::RouterDeclined + | AttemptStatus::AuthorizationFailed + | AttemptStatus::Voided + | AttemptStatus::CaptureFailed + | AttemptStatus::Failure + | AttemptStatus::AutoRefunded => Some(false), + + AttemptStatus::AuthenticationSuccessful + | AttemptStatus::PartialChargedAndChargeable + | AttemptStatus::Authorized + | AttemptStatus::Charged => Some(true), + + AttemptStatus::Started + | AttemptStatus::AuthenticationPending + | AttemptStatus::Authorizing + | AttemptStatus::CodInitiated + | AttemptStatus::VoidInitiated + | AttemptStatus::CaptureInitiated + | AttemptStatus::VoidFailed + | AttemptStatus::PartialCharged + | AttemptStatus::Unresolved + | AttemptStatus::Pending + | AttemptStatus::PaymentMethodAwaited + | AttemptStatus::ConfirmationAwaited + | AttemptStatus::DeviceDataCollectionPending => None, + } + } +} + +#[cfg(feature = "frm")] +pub trait FraudCheckCheckoutRequest { + fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; +} + +#[cfg(feature = "frm")] +impl FraudCheckCheckoutRequest for FraudCheckCheckoutData { + fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { + self.order_details + .clone() + .ok_or_else(missing_field_err("order_details")) + } +} + +#[cfg(feature = "frm")] +pub trait FraudCheckTransactionRequest { + fn get_currency(&self) -> Result<enums::Currency, Error>; +} +#[cfg(feature = "frm")] +impl FraudCheckTransactionRequest for FraudCheckTransactionData { + fn get_currency(&self) -> Result<enums::Currency, Error> { + self.currency.ok_or_else(missing_field_err("currency")) + } +} /// Custom deserializer for Option<Currency> that treats empty strings as None pub fn deserialize_optional_currency<'de, D>( diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e398800788c..46f63abf501 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -103,7 +103,6 @@ serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" serde_path_to_error = "0.1.16" serde_qs = "0.12.0" -serde_repr = "0.1.19" serde_urlencoded = "0.7.1" serde_with = "3.7.0" sha1 = { version = "0.10.6" } diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 0c4b4be1793..e78c64d6fe9 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -4,10 +4,7 @@ pub mod dummyconnector; pub mod ebanx; pub mod gpayments; pub mod netcetera; -pub mod nmi; -pub mod payone; pub mod plaid; -pub mod riskified; pub mod signifyd; pub mod stripe; pub mod threedsecureio; @@ -33,12 +30,13 @@ pub use hyperswitch_connectors::connectors::{ itaubank::Itaubank, jpmorgan, jpmorgan::Jpmorgan, juspaythreedsserver, juspaythreedsserver::Juspaythreedsserver, klarna, klarna::Klarna, mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris, moneris::Moneris, multisafepay, multisafepay::Multisafepay, - nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, noon, - noon::Noon, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, - opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payme, payme::Payme, - paypal, paypal::Paypal, paystack, paystack::Paystack, payu, payu::Payu, placetopay, - placetopay::Placetopay, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, - rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly::Recurly, redsys, redsys::Redsys, + nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nmi, nmi::Nmi, nomupay, + nomupay::Nomupay, noon, noon::Noon, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, + opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, + payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, paystack, + paystack::Paystack, payu, payu::Payu, placetopay, placetopay::Placetopay, powertranz, + powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, + razorpay::Razorpay, recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, trustpay, trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service, @@ -51,6 +49,6 @@ pub use hyperswitch_connectors::connectors::{ pub use self::dummyconnector::DummyConnector; pub use self::{ adyenplatform::Adyenplatform, ebanx::Ebanx, gpayments::Gpayments, netcetera::Netcetera, - nmi::Nmi, payone::Payone, plaid::Plaid, riskified::Riskified, signifyd::Signifyd, - stripe::Stripe, threedsecureio::Threedsecureio, wellsfargopayout::Wellsfargopayout, wise::Wise, + plaid::Plaid, signifyd::Signifyd, stripe::Stripe, threedsecureio::Threedsecureio, + wellsfargopayout::Wellsfargopayout, wise::Wise, }; diff --git a/crates/router/src/connector/riskified/transformers/auth.rs b/crates/router/src/connector/riskified/transformers/auth.rs deleted file mode 100644 index 6968bb55a59..00000000000 --- a/crates/router/src/connector/riskified/transformers/auth.rs +++ /dev/null @@ -1,22 +0,0 @@ -use error_stack; -use masking::{ExposeInterface, Secret}; - -use crate::{core::errors, types}; - -pub struct RiskifiedAuthType { - pub secret_token: Secret<String>, - pub domain_name: String, -} - -impl TryFrom<&types::ConnectorAuthType> for RiskifiedAuthType { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - match auth_type { - types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { - secret_token: api_key.to_owned(), - domain_name: key1.to_owned().expose(), - }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), - } - } -} diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index afee6a42b14..cd2740d2803 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -225,9 +225,7 @@ default_imp_for_complete_authorize!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -265,10 +263,7 @@ default_imp_for_webhook_source_verification!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -308,10 +303,7 @@ default_imp_for_create_customer!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -352,9 +344,7 @@ default_imp_for_connector_redirect_response!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -377,10 +367,7 @@ default_imp_for_connector_request_id!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -423,10 +410,7 @@ default_imp_for_accept_dispute!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -488,10 +472,7 @@ default_imp_for_file_upload!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -530,10 +511,7 @@ default_imp_for_submit_evidence!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -572,10 +550,7 @@ default_imp_for_defend_dispute!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -630,9 +605,7 @@ default_imp_for_pre_processing_steps!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -654,13 +627,10 @@ impl<const T: u8> default_imp_for_post_processing_steps!( connector::Adyenplatform, - connector::Nmi, connector::Stripe, connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Payone, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -681,9 +651,7 @@ impl<const T: u8> Payouts for connector::DummyConnector<T> {} default_imp_for_payouts!( connector::Gpayments, connector::Netcetera, - connector::Nmi, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -721,10 +689,7 @@ default_imp_for_payouts_create!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -763,10 +728,7 @@ default_imp_for_payouts_retrieve!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -809,10 +771,7 @@ default_imp_for_payouts_eligibility!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -850,9 +809,7 @@ impl<const T: u8> default_imp_for_payouts_fulfill!( connector::Gpayments, connector::Netcetera, - connector::Nmi, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -890,10 +847,7 @@ default_imp_for_payouts_cancel!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -931,10 +885,7 @@ default_imp_for_payouts_quote!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -973,10 +924,7 @@ default_imp_for_payouts_recipient!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout @@ -1018,10 +966,7 @@ default_imp_for_payouts_recipient_account!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -1060,10 +1005,7 @@ default_imp_for_approve!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1103,10 +1045,7 @@ default_imp_for_reject!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1131,9 +1070,7 @@ default_imp_for_fraud_check!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, - connector::Nmi, connector::Netcetera, - connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, @@ -1175,8 +1112,6 @@ default_imp_for_frm_sale!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, @@ -1218,8 +1153,6 @@ default_imp_for_frm_checkout!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, @@ -1261,8 +1194,6 @@ default_imp_for_frm_transaction!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, @@ -1304,8 +1235,6 @@ default_imp_for_frm_fulfillment!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, @@ -1347,8 +1276,6 @@ default_imp_for_frm_record_return!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, @@ -1388,10 +1315,7 @@ default_imp_for_incremental_authorization!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1429,10 +1353,7 @@ default_imp_for_revoking_mandates!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1528,10 +1449,7 @@ impl<const T: u8> default_imp_for_connector_authentication!( connector::Adyenplatform, connector::Ebanx, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Wellsfargopayout, @@ -1567,10 +1485,7 @@ default_imp_for_authorize_session_token!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1608,10 +1523,7 @@ default_imp_for_calculate_tax!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1649,10 +1561,7 @@ default_imp_for_session_update!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1690,10 +1599,7 @@ default_imp_for_post_session_tokens!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1731,10 +1637,7 @@ default_imp_for_update_metadata!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, @@ -1774,10 +1677,7 @@ default_imp_for_uas_pre_authentication!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1815,10 +1715,7 @@ default_imp_for_uas_post_authentication!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1845,10 +1742,7 @@ default_imp_for_uas_authentication_confirmation!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -1899,10 +1793,7 @@ default_imp_for_uas_authentication!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -2035,10 +1926,8 @@ default_imp_for_revenue_recovery! { connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, + connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -2080,10 +1969,7 @@ default_imp_for_billing_connector_payment_sync!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, @@ -2125,10 +2011,7 @@ default_imp_for_revenue_recovery_record_back!( connector::Ebanx, connector::Gpayments, connector::Netcetera, - connector::Nmi, - connector::Payone, connector::Plaid, - connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, diff --git a/crates/router/src/macros.rs b/crates/router/src/macros.rs index 580ccb73f53..c6de30c8d0f 100644 --- a/crates/router/src/macros.rs +++ b/crates/router/src/macros.rs @@ -1,15 +1,5 @@ pub use common_utils::{collect_missing_value_keys, newtype}; -#[macro_export] -macro_rules! get_formatted_date_time { - ($date_format:tt) => {{ - let format = time::macros::format_description!($date_format); - time::OffsetDateTime::now_utc() - .format(&format) - .change_context($crate::core::errors::ConnectorError::InvalidDateFormat) - }}; -} - #[macro_export] macro_rules! get_payment_link_config_value_based_on_priority { ($config:expr, $business_config:expr, $field:ident, $default:expr) => {
2025-03-28T10:39:38Z
## 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 --> Moving connectors (NMI,Riskified,and payone) from `router` crate to `hyperswitch_connector` crate ### 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 Closes #7715 # NMI test ## Create payment processor NOTE: used 3ds enabled key ```json { "connector_type": "payment_processor", "connector_name": "nmi", "connector_account_details": { "api_key":"********************", "auth_type": "BodyKey", "key1": "***********************" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" } ``` ## Create payment processor Response ```json { "connector_type": "payment_processor", "connector_name": "nmi", "connector_label": "nmi_US_default", "merchant_connector_id": "mca_sZo4dKynSU90CRdytdQT", "profile_id": "pro_5wu4McY9AIOVmllRswYz", "connector_account_details": { "auth_type": "BodyKey", "api_key": "***************************", "key1": "********************************************" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret", "additional_secret": null }, "metadata": { "city": "NY", "unit": "245" }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null } ``` ## create payment ```json { "amount": 250, "currency": "USD", "confirm": true, "amount_to_capture": 250, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "nithin", "email": "[email protected]", "name": "John Doe", "phone": "9731918444", "phone_country_code": "+91", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "routing": { "type": "single", "data": "nmi" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4000000000002503", "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "999" } }, "billing": { "address": { "zip": "560095", "country": "IN", "first_name": "Sakil", "last_name": "Mostak" } } } ``` ## create payment response ```json { "payment_id": "pay_9hrmW9oFfnKedAy0P3Mn", "merchant_id": "merchant_1743143179", "status": "requires_customer_action", "amount": 250, "net_amount": 250, "shipping_cost": null, "amount_capturable": 250, "amount_received": null, "connector": "nmi", "client_secret": "pay_9hrmW9oFfnKedAy0P3Mn_secret_gJqo6Tw0eee5XPrufvo1", "created": "2025-03-28T10:29:46.830Z", "currency": "USD", "customer_id": "johndoe", "customer": { "id": "johndoe", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+91" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "2503", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_Qgf7HooZS0DBdeTuvyW2", "shipping": { "address": { "city": null, "country": "US", "line1": null, "line2": null, "line3": null, "zip": "94122", "state": null, "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": null, "country": "IN", "line1": null, "line2": null, "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_9hrmW9oFfnKedAy0P3Mn/merchant_1743143179/pay_9hrmW9oFfnKedAy0P3Mn_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "johndoe", "created_at": 1743157786, "expires": 1743161386, "secret": "epk_46f549a6894b47b5bb741de8aa1381b5" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "", "payment_link": null, "profile_id": "pro_5wu4McY9AIOVmllRswYz", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_sZo4dKynSU90CRdytdQT", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-28T10:44:46.830Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-28T10:29:48.266Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "issuer_error_code": null, "issuer_error_message": null } ``` Open redirect url "http://localhost:8080/payments/redirect/pay_9hrmW9oFfnKedAy0P3Mn/merchant_1743143179/pay_9hrmW9oFfnKedAy0P3Mn_1" <img width="1680" alt="Screenshot 2025-03-28 at 4 01 28 PM" src="https://github.com/user-attachments/assets/075f5bd4-c04c-4927-83dd-744d64f8a59b" /> ## payment retrieve NOTE use `/payments/:id?force_sync=true` Response ```json { "payment_id": "pay_9hrmW9oFfnKedAy0P3Mn", "merchant_id": "merchant_1743143179", "status": "succeeded", "amount": 250, "net_amount": 250, "shipping_cost": null, "amount_capturable": 0, "amount_received": 250, "connector": "nmi", "client_secret": "pay_9hrmW9oFfnKedAy0P3Mn_secret_gJqo6Tw0eee5XPrufvo1", "created": "2025-03-28T10:29:46.830Z", "currency": "USD", "customer_id": "johndoe", "customer": { "id": "johndoe", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+91" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "2503", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_Qgf7HooZS0DBdeTuvyW2", "shipping": { "address": { "city": null, "country": "US", "line1": null, "line2": null, "line3": null, "zip": "94122", "state": null, "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": null, "country": "IN", "line1": null, "line2": null, "line3": null, "zip": "560095", "state": null, "first_name": "Sakil", "last_name": "Mostak" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "10550766500", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_9hrmW9oFfnKedAy0P3Mn_1", "payment_link": null, "profile_id": "pro_5wu4McY9AIOVmllRswYz", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_sZo4dKynSU90CRdytdQT", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-28T10:44:46.830Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-28T10:34:49.994Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "issuer_error_code": null, "issuer_error_message": null } ``` ## refunds ```json "payment_id": "pay_9hrmW9oFfnKedAy0P3Mn", "amount": 250, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` Response ```json { "refund_id": "ref_rOGRIeo7mSWazFxB6TpF", "payment_id": "pay_9hrmW9oFfnKedAy0P3Mn", "amount": 250, "currency": "USD", "status": "pending", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-03-28T10:36:26.792Z", "updated_at": "2025-03-28T10:36:29.898Z", "connector": "nmi", "profile_id": "pro_5wu4McY9AIOVmllRswYz", "merchant_connector_id": "mca_sZo4dKynSU90CRdytdQT", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ## refund retrieve response ```json { "refund_id": "ref_rOGRIeo7mSWazFxB6TpF", "payment_id": "pay_9hrmW9oFfnKedAy0P3Mn", "amount": 250, "currency": "USD", "status": "succeeded", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-03-28T10:36:26.792Z", "updated_at": "2025-03-28T10:36:54.546Z", "connector": "nmi", "profile_id": "pro_5wu4McY9AIOVmllRswYz", "merchant_connector_id": "mca_sZo4dKynSU90CRdytdQT", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` ********************************************** PAYONE ****************************** ## create connector ```json { "connector_type": "payout_processor", "connector_name": "payone", "connector_label": "adyen_payouts", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "*********************", "api_secret": "**********************", "key1": "Hyperswitch" }, "test_mode": true, "disabled": false, "metadata": { "city": "NY", "unit": "245", "endpoint_prefix": "" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "credit", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ] } ``` ## create payouts ```json { "amount": 100, "currency": "EUR", "profile_id": {{profile_id}}, "customer": { "id": "new_id", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65" }, "connector": [ "payone" ], "description": "Its my first payout request", "payout_type": "card", "payout_method_data": { "card": { "card_number": "5137009801943438", "expiry_month": "03", "expiry_year": "2030", "card_holder_name": "John Doe" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "confirm": true, "auto_fulfill": true } ``` # RISKIFIED - Create a merchant with frm_routing_algorithm ```json "frm_routing_algorithm": { "type": "single", "data": "riskified" } ``` - create stripe MCA - create RISKIFIED MCA ```json { "connector_type": "payment_vas", "connector_name": "riskified", "connector_account_details": { "auth_type": "BodyKey", "api_key": "*************APIKEY", "key1": "www.juspay.com" }, "connector_webhook_details": { "merchant_secret": "**********************MERCHANT_SECRET", "additional_secret": null }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" }, "frm_configs": [ { "gateway": "stripe", "payment_methods": [ { "payment_method": "card", "flow" : "pre" } ] } ] } ``` - create a payment ```json { "amount": 1500000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1500000, "customer_id": "StripeCustomer2", "email": "[email protected]", "name": "Bob Smith", "phone": "999999999", "phone_country_code": "+91", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "31 Sherwood Gardens", "line3": "31 Sherwood Gardens", "city": "London", "state": "Manchester", "zip": "E14 9wn", "country": "GB", "first_name": "Bob", "last_name": "Smith" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "order_details" : [{ "product_name" : "gillete creme", "quantity" : 2, "amount" : 600 }, { "product_name" : "gillete razor", "quantity" : 1, "amount" : 300 }], "frm_metadata": { "vendor_name": "srujan", "shipping_lines": [ ] } } ``` - payment message should contain `frm_message` from riskified ```json "frm_message": { "frm_name": "riskified", "frm_transaction_id": "pay_v2TLKee8Wlw84rC7IHsj_1", "frm_transaction_type": "pre_frm", "frm_status": "legit", "frm_score": null, "frm_reason": "Reviewed and approved by Riskified", "frm_error": null } ```
v1.113.0
50cbe20ee1da0392f4f590bade9f866435356b87
50cbe20ee1da0392f4f590bade9f866435356b87
juspay/hyperswitch
juspay__hyperswitch-7691
Bug: refactor(cypress): BOA testcases are failing due to failed assertions of Refunds and Connector Agnostic
2025-04-02T08:19:33Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> Refunds for Manually Captured No3DS Payments and Connector Agnostic NTID Test Cases in Cypress were failing for `Bank of America` Payment Processor. - The Refunds for Manually Captured No3DS Payments were staying in `pending` status instead of `succeeded` with `error_message` as `null` and on RSync, it yields `errorInformation.message` as `"Request was processed successfully."` with status still as `pending`. - The `00024-ConnectorAgnosticNTID` was failing with the error message in the response as `"No eligible connector was found for the current payment method configuration"` because it did not support Connector Agnostic. So, made the following changes:- - Mapped the status accordingly. Changed `succeeded` to `pending` for No3DS Manual Payment Refunds. - Excluded `bankofamerica` from the Connectors which are allowing Connector Agnostic. ### 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). --> Bank of America Cypress Test Cases were failing. ## 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="718" alt="image" src="https://github.com/user-attachments/assets/440774ed-944e-4a10-8447-4fa75e05e915" /> _(Tested on Integ Environment)_ ## 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.113.0
961c875ecc225c924160448f01bf38a8e5a4ca03
961c875ecc225c924160448f01bf38a8e5a4ca03
juspay/hyperswitch
juspay__hyperswitch-7694
Bug: Default value for `forex_enabled` if config is not set Currently, if the `forex_enabled` flag is not present as an ENV, it is leading to deserialization errors. Need to modify it in such a way to assume the default value (false) if the ENV is not present.
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 89f5cbd5b9c..2cd2da30e45 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -1010,25 +1010,28 @@ impl AnalyticsProvider { } #[derive(Clone, Debug, serde::Deserialize)] -#[serde(tag = "source")] -#[serde(rename_all = "lowercase")] +#[serde(tag = "source", rename_all = "lowercase")] pub enum AnalyticsConfig { Sqlx { sqlx: Database, + #[serde(default)] forex_enabled: bool, }, Clickhouse { clickhouse: ClickhouseConfig, + #[serde(default)] forex_enabled: bool, }, CombinedCkh { sqlx: Database, clickhouse: ClickhouseConfig, + #[serde(default)] forex_enabled: bool, }, CombinedSqlx { sqlx: Database, clickhouse: ClickhouseConfig, + #[serde(default)] forex_enabled: bool, }, }
2025-04-02T09:12:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently, if the `forex_enabled` feature flag is not present as an ENV, it is leading to deserialization errors. Modified it in such a way to assume the default value (false) if the ENV is not present. ### 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). --> Fix deserialization errors for analytics ## 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)? --> Removed the `forex_enabled` feature flag from local envs, and replicated the error <img width="806" alt="Screenshot 2025-04-02 at 2 34 43 PM" src="https://github.com/user-attachments/assets/b275cc79-1fad-4ee7-81a5-acaf780e771c" /> Need to remove the env `forex_enabled` during deployment, and then test out the analytics section.. Tested on local, by removing the `forex_enabled` env and checking the analytics API calls, worked as expected <img width="638" alt="image" src="https://github.com/user-attachments/assets/56ba5d51-ff1c-4d42-8401-ea00e7bc6d22" /> Curl: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiM2RlMDFhYWYtOWVkMi00YTY5LTg3YWItNWU1YmI2ZWFiNGQ5IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQyMjEyMzQxIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Mjk4MDgyOCwib3JnX2lkIjoib3JnX3pMQmRNTnpLaDZrNmhiT2tockdJIiwicHJvZmlsZV9pZCI6InByb19LWnhHZ21rUHFkMldQdXBFa2psWCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.aD185AZEOcIjHnLnZZ9GJ2ujSHIdRPbPtrYhzNo0V4M' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2025-03-01T18:30:00Z", "endTime": "2025-03-31T09:22:00Z" }, "source": "BATCH", "metrics": [ "payment_processed_amount" ], "timeSeries": { "granularity": "G_ONEDAY" }, "delta": true } ]' ``` ## 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.113.0
cfe226943dc5b473e88b7830c54ac73a943ba04b
cfe226943dc5b473e88b7830c54ac73a943ba04b
juspay/hyperswitch
juspay__hyperswitch-7685
Bug: Missing next steps after deployment setup on Readme Next steps after deployment setup on Readme are missing
diff --git a/README.md b/README.md index 5b5518d31fc..72ac7e0e3a7 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,13 @@ Check out the [local setup guide][local-setup-guide] for a more details on setti Attaching to hyperswitch-control-center-1, hyperswitch-server-1, hyperswitch-web-1, migration_runner-1, pg-1, redis-standalone-1 ``` +You've now setup Hyperswitch in your local machine. In order to verify that the server is up and running hit the health endpoint: +```shell +curl --head --request GET 'http://localhost:8080/health' +``` +The expected response here is a `200 OK` status code. This indicates that the server and all of its dependent services are functioning correctly. +Now, you can access the Control Center in your browser at `http://localhost:9000`. +The next step is to configure a connector with the Hyperswitch Control Center and try a payment. ### 2. Deployment on cloud
2025-04-01T21:15:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [X] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Updated next steps after deployment setup on Readme ### 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). --> Updated next steps after deployment setup on Readme closes : #7685 7685 ## 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.113.0
446716ee20440c1937c1b988b2ea3ce58d23089c
446716ee20440c1937c1b988b2ea3ce58d23089c
juspay/hyperswitch
juspay__hyperswitch-7680
Bug: [BUG] Improper use of innerHTML in payment links Payment links make use of innerHTML property for rendering a bunch a user's text based inputs. This is considered unsafe since innerHTML evaluates the input as HTML and can lead to cross side scripting. Update this to use textContent rather than using innerHTML for rendering text based user inputs.
diff --git a/crates/hyperswitch_domain_models/src/api.rs b/crates/hyperswitch_domain_models/src/api.rs index 571371dc63c..f6d93497627 100644 --- a/crates/hyperswitch_domain_models/src/api.rs +++ b/crates/hyperswitch_domain_models/src/api.rs @@ -72,7 +72,7 @@ pub enum PaymentLinkAction { pub struct PaymentLinkFormData { pub js_script: String, pub css_script: String, - pub sdk_url: String, + pub sdk_url: url::Url, pub html_meta_tags: String, } @@ -127,7 +127,7 @@ pub struct GenericExpiredLinkData { pub struct GenericLinkFormData { pub js_data: String, pub css_data: String, - pub sdk_url: String, + pub sdk_url: url::Url, pub html_meta_tags: String, } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index fb40451888f..8e1fb35ddce 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -444,9 +444,19 @@ impl Default for GenericLinkEnvUiConfig { } } -#[derive(Debug, Deserialize, Clone, Default)] +#[derive(Debug, Deserialize, Clone)] pub struct PaymentLink { - pub sdk_url: String, + pub sdk_url: url::Url, +} + +impl Default for PaymentLink { + fn default() -> Self { + Self { + #[allow(clippy::expect_used)] + sdk_url: url::Url::parse("https://beta.hyperswitch.io/v0/HyperLoader.js") + .expect("Failed to parse default SDK URL"), + } + } } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index adcfe8046de..545966968bd 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -387,12 +387,11 @@ pub async fn initiate_secure_payment_link_flow( payment_form_label_type: payment_link_config.payment_form_label_type, show_card_terms: payment_link_config.show_card_terms, }; - let js_script = format!( - "window.__PAYMENT_DETAILS = {}", - serde_json::to_string(&secure_payment_link_details) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to serialize PaymentLinkData")? - ); + let payment_details_str = serde_json::to_string(&secure_payment_link_details) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize PaymentLinkData")?; + let url_encoded_str = urlencoding::encode(&payment_details_str); + let js_script = format!("window.__PAYMENT_DETAILS = '{}';", url_encoded_str); let html_meta_tags = get_meta_tags_html(&link_details); let payment_link_data = services::PaymentLinkFormData { js_script, @@ -491,7 +490,8 @@ fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> { let payment_details_str = serde_json::to_string(payment_details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentLinkData")?; - Ok(format!("window.__PAYMENT_DETAILS = {payment_details_str};")) + let url_encoded_str = urlencoding::encode(&payment_details_str); + Ok(format!("window.__PAYMENT_DETAILS = '{url_encoded_str}';")) } fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String { diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js index bdfdfa8a8bf..1e96731402f 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js @@ -1,9 +1,19 @@ -// @ts-nocheck +// @ts-check /** * UTIL FUNCTIONS */ +function decodeUri(uri) { + try { + var uriStr = decodeURIComponent(uri); + return JSON.parse(uriStr); + } catch (e) { + console.error("Error decoding and parsing string URI:", e); + return uri; + } +} + function adjustLightness(hexColor, factor) { // Convert hex to RGB var r = parseInt(hexColor.slice(1, 3), 16); @@ -176,10 +186,13 @@ window.state = { var widgets = null; var unifiedCheckout = null; // @ts-ignore -var pub_key = window.__PAYMENT_DETAILS.pub_key; +var encodedPaymentDetails = window.__PAYMENT_DETAILS; +var paymentDetails = decodeUri(encodedPaymentDetails); +var pub_key = paymentDetails.pub_key; var hyper = null; -const translations = getTranslations(window.__PAYMENT_DETAILS.locale); +// @ts-ignore +const translations = getTranslations(paymentDetails.locale); var isFramed = false; try { @@ -215,10 +228,6 @@ function emitPaymentStatus(paymentDetails) { * - Initialize SDK **/ function boot() { - - // @ts-ignore - var paymentDetails = window.__PAYMENT_DETAILS; - // Emit latest payment status if (isFramed) { emitPaymentStatus(paymentDetails); @@ -435,7 +444,7 @@ function initializeEventListeners(paymentDetails) { if (paymentForm instanceof HTMLFormElement) { paymentForm.addEventListener("submit", function (event) { event.preventDefault(); - handleSubmit(event); + handleSubmit(event, paymentDetails); }) } @@ -447,18 +456,20 @@ function initializeEventListeners(paymentDetails) { function handleFormReadyForSubmission() { window.addEventListener("message", function (event) { // Event listener for updating the button rules - if (isObject(event.data) && event.data["isFormReadyForSubmission"] !== null) { - let isFormReadyForSubmission = event.data["isFormReadyForSubmission"]; - var submitButtonNode = document.getElementById("submit"); - if (submitButtonNode instanceof HTMLButtonElement) { - if (isFormReadyForSubmission === false) { - submitButtonNode.disabled = true; - addClass("#submit", "not-ready"); - addClass("#submit", "disabled"); - } else if (isFormReadyForSubmission === true) { - submitButtonNode.disabled = false; - removeClass("#submit", "not-ready"); - removeClass("#submit", "disabled"); + if (event.origin == "{{sdk_origin}}") { + if (isObject(event.data) && event.data["isFormReadyForSubmission"] !== null) { + let isFormReadyForSubmission = event.data["isFormReadyForSubmission"]; + var submitButtonNode = document.getElementById("submit"); + if (submitButtonNode instanceof HTMLButtonElement) { + if (isFormReadyForSubmission === false) { + submitButtonNode.disabled = true; + addClass("#submit", "not-ready"); + addClass("#submit", "disabled"); + } else if (isFormReadyForSubmission === true) { + submitButtonNode.disabled = false; + removeClass("#submit", "not-ready"); + removeClass("#submit", "disabled"); + } } } } @@ -504,12 +515,10 @@ function mountUnifiedCheckout(id) { * - Toggle UI loaders appropriately * - Handle errors and redirect to status page * @param {Event} e + * @param {PaymentDetails} paymentDetails */ // @ts-ignore -function handleSubmit(e) { - // @ts-ignore - var paymentDetails = window.__PAYMENT_DETAILS; - +function handleSubmit(e, paymentDetails) { // Update button loader hide("#submit-button-text"); show("#submit-spinner"); @@ -553,7 +562,7 @@ function handleSubmit(e) { url.search = params.toString(); window.top.location.href = url.toString(); } else { - redirectToStatus(); + redirectToStatus(paymentDetails); } }) .catch(function (error) { @@ -772,25 +781,33 @@ function appendMerchantDetails(paymentDetails, merchantDynamicDetails) { ); var horizontalLine = document.createElement("hr"); horizontalLine.className = "hyper-checkout-payment-horizontal-line"; - horizontalLineContainer.append(horizontalLine); + if (horizontalLineContainer instanceof HTMLDivElement) { + horizontalLineContainer.append(horizontalLine); + } // max number of items to show in the merchant details let maxItemsInDetails = 50; for (var item of merchantDetailsObject) { var merchantData = document.createElement("div"); merchantData.className = "hyper-checkout-payment-merchant-dynamic-data"; + var keyNode = document.createElement("span"); + keyNode.textContent = item.key; + var valueNode = document.createElement("span"); + valueNode.textContent = item.value; // make the key and value bold if specified in the ui_configuration - var key = item.ui_configuration - ? item.ui_configuration.is_key_bold - ? item.key.bold() - : item.key - : item.key; - var value = item.ui_configuration - ? item.ui_configuration.is_value_bold - ? item.value.bold() - : item.value - : item.value; - merchantData.innerHTML = key + " : " + value; + if (isObject(item.ui_configuration)) { + if (item.ui_configuration.is_key_bold) { + keyNode.style.fontWeight = "bold"; + } + if (item.ui_configuration.is_value_bold) { + valueNode.style.fontWeight = "bold"; + } + } + var separatorNode = document.createElement("span"); + separatorNode.textContent = " : "; + merchantData.appendChild(keyNode); + merchantData.appendChild(separatorNode); + merchantData.appendChild(valueNode); merchantDynamicDetails.append(merchantData); if (--maxItemsInDetails === 0) { diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js index effd27cc64a..33758131aa2 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js @@ -9,7 +9,8 @@ **/ function initializeSDK() { // @ts-ignore - var paymentDetails = window.__PAYMENT_DETAILS; + var encodedPaymentDetails = window.__PAYMENT_DETAILS; + var paymentDetails = decodeUri(encodedPaymentDetails); var clientSecret = paymentDetails.client_secret; var sdkUiRules = paymentDetails.sdk_ui_rules; var labelType = paymentDetails.payment_form_label_type; @@ -99,8 +100,7 @@ function initializeSDK() { /** * Use - redirect to /payment_link/status */ -function redirectToStatus() { - var paymentDetails = window.__PAYMENT_DETAILS; +function redirectToStatus(paymentDetails) { var arr = window.location.pathname.split("/"); // NOTE - This code preserves '/api' in url for integ and sbx diff --git a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js index 446428e6ff3..3db5eb94de2 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js @@ -123,8 +123,7 @@ if (!isFramed) { /** * Use - redirect to /payment_link/status */ - function redirectToStatus() { - var paymentDetails = window.__PAYMENT_DETAILS; + function redirectToStatus(paymentDetails) { var arr = window.location.pathname.split("/"); // NOTE - This code preserves '/api' in url for integ and sbx envs diff --git a/crates/router/src/core/payment_link/payment_link_status/status.js b/crates/router/src/core/payment_link/payment_link_status/status.js index 16949d546a6..371fdf1d2df 100644 --- a/crates/router/src/core/payment_link/payment_link_status/status.js +++ b/crates/router/src/core/payment_link/payment_link_status/status.js @@ -4,6 +4,16 @@ * UTIL FUNCTIONS */ +function decodeUri(uri) { + try { + var uriStr = decodeURIComponent(uri); + return JSON.parse(uriStr); + } catch (e) { + console.error("Error decoding and parsing string URI:", e); + return uri; + } +} + /** * Ref - https://github.com/onury/invert-color/blob/master/lib/cjs/invert.js */ @@ -86,7 +96,12 @@ window.state = { isMobileView: window.innerWidth <= 1400, }; -const translations = getTranslations(window.__PAYMENT_DETAILS.locale); +// @ts-ignore +var encodedPaymentDetails = window.__PAYMENT_DETAILS; +var paymentDetails = decodeUri(encodedPaymentDetails); + +// @ts-ignore +const translations = getTranslations(paymentDetails.locale); var isFramed = false; try { @@ -122,9 +137,6 @@ function emitPaymentStatus(paymentDetails) { * - Initialize SDK **/ function boot() { - // @ts-ignore - var paymentDetails = window.__PAYMENT_DETAILS; - // Emit latest payment status if (isFramed) { emitPaymentStatus(paymentDetails); @@ -272,7 +284,7 @@ function renderStatusDetails(paymentDetails) { var merchantLogoNode = document.createElement("img"); merchantLogoNode.className = "hyper-checkout-status-merchant-logo"; // @ts-ignore - merchantLogoNode.src = window.__PAYMENT_DETAILS.merchant_logo; + merchantLogoNode.src = paymentDetails.merchant_logo; merchantLogoNode.alt = ""; // Form content items diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 4a2b3d75204..7e13dbbed16 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -400,7 +400,7 @@ pub async fn render_pm_collect_link( let generic_form_data = services::GenericLinkFormData { js_data: serialized_js_content, css_data: serialized_css_content, - sdk_url: default_config.sdk_url.to_string(), + sdk_url: default_config.sdk_url.clone(), html_meta_tags: String::new(), }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs index 063529e21fe..06edca897dc 100644 --- a/crates/router/src/core/payout_link.rs +++ b/crates/router/src/core/payout_link.rs @@ -260,7 +260,7 @@ pub async fn initiate_payout_link( let generic_form_data = services::GenericLinkFormData { js_data: serialized_js_content, css_data: serialized_css_content, - sdk_url: default_config.sdk_url.to_string(), + sdk_url: default_config.sdk_url.clone(), html_meta_tags: String::new(), }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 76a2b9e50e6..2ae0c68ccef 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1877,6 +1877,30 @@ fn build_payment_link_template( let _ = tera.add_raw_template("payment_link_js", &js_template); context.insert("payment_details_js_script", &payment_link_data.js_script); + let sdk_origin = payment_link_data + .sdk_url + .host_str() + .ok_or_else(|| { + logger::error!("Host missing for payment link SDK URL"); + report!(errors::ApiErrorResponse::InternalServerError) + }) + .and_then(|host| { + if host == "localhost" { + let port = payment_link_data.sdk_url.port().ok_or_else(|| { + logger::error!("Port missing for localhost in SDK URL"); + report!(errors::ApiErrorResponse::InternalServerError) + })?; + Ok(format!( + "{}://{}:{}", + payment_link_data.sdk_url.scheme(), + host, + port + )) + } else { + Ok(format!("{}://{}", payment_link_data.sdk_url.scheme(), host)) + } + })?; + context.insert("sdk_origin", &sdk_origin); let rendered_js = match tera.render("payment_link_js", &context) { Ok(rendered_js) => rendered_js, @@ -1954,11 +1978,11 @@ pub fn build_secure_payment_link_html( .attach_printable("Error while rendering secure payment link's HTML template") } -fn get_hyper_loader_sdk(sdk_url: &str) -> String { +fn get_hyper_loader_sdk(sdk_url: &url::Url) -> String { format!("<script src=\"{sdk_url}\" onload=\"initializeSDK()\"></script>") } -fn get_preload_link_html_template(sdk_url: &str) -> String { +fn get_preload_link_html_template(sdk_url: &url::Url) -> String { format!( r#"<link rel="preload" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800" as="style"> <link rel="preload" href="{sdk_url}" as="script">"#,
2025-04-07T10:15:29Z
## 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 below issues specifically for payment links - improper use of innerHTML for API inputs - for rendering transaction details - improper use of receiving event (isFormReadyForSubmission) from HS SDK Overall, this PR sanitizes API text based inputs which are rendered in the payment link UI using URI encoding before rendering the payment link HTML response. The URI encoded data is decoded in JS runtime (browser) and consumed whenever required. ### 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 locally <details> <summary>1. Create payment links and process redirection based txns (3DS)</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ML2p8kRGcMvi4oQ3cPnIfz5R2rO31efjWKXzgMnbRCnj5pUpjiki8K2HONlmMAb4' \ --data-raw '{"authentication_type":"three_ds","customer_id":"cus_9SCrW9x19m2WbGYHprJS","profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","amount":100,"currency":"EUR","payment_link":true,"setup_future_usage":"off_session","capture_method":"automatic","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"NL","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"return_url":"https://example.com","payment_link_config":{"theme":"#003264","skip_status_screen":true,"transaction_details":[{"key":"a","value":"<script href=\"https://www.somesite.com\"></script>","ui_configuration":{"is_key_bold":true,"is_value_bold":true}}],"background_image":{"url":"https://img.freepik.com/free-photo/abstract-blue-geometric-shapes-background_24972-1841.jpg","position":"bottom","size":"cover"}}}' Response {"payment_id":"pay_DrqIRGsc6hs4BP3GVe56","merchant_id":"merchant_1743758708","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_DrqIRGsc6hs4BP3GVe56_secret_5g2zaDCBZlK5ebBSQnF7","created":"2025-04-07T10:11:02.890Z","currency":"EUR","customer_id":"cus_9SCrW9x19m2WbGYHprJS","customer":{"id":"cus_9SCrW9x19m2WbGYHprJS","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"NL","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_9SCrW9x19m2WbGYHprJS","created_at":1744020662,"expires":1744024262,"secret":"epk_e9bec308a59f4550adf8dd6b7b57506f"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1743758708/pay_DrqIRGsc6hs4BP3GVe56?locale=en","secure_link":"http://localhost:8080/payment_link/s/merchant_1743758708/pay_DrqIRGsc6hs4BP3GVe56?locale=en","payment_link_id":"plink_qOUNfvUvtkTK7K8sXBoU"},"profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-07T10:26:02.875Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-07T10:11:02.944Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"issuer_error_code":null,"issuer_error_message":null} Verify below things 1. Redirection works as expected 2. Payment journey is as expected </details> <details> <summary>2. Create payment links and process redirection based txns (3DS)</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ML2p8kRGcMvi4oQ3cPnIfz5R2rO31efjWKXzgMnbRCnj5pUpjiki8K2HONlmMAb4' \ --data-raw '{"authentication_type":"three_ds","customer_id":"cus_9SCrW9x19m2WbGYHprJS","profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","amount":100,"currency":"EUR","payment_link":true,"setup_future_usage":"off_session","capture_method":"automatic","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"NL","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"return_url":"https://example.com","payment_link_config":{"theme":"#003264","skip_status_screen":true,"transaction_details":[{"key":"a","value":"<script href=\"https://www.somesite.com\"></script>","ui_configuration":{"is_key_bold":true,"is_value_bold":true}}],"background_image":{"url":"https://img.freepik.com/free-photo/abstract-blue-geometric-shapes-background_24972-1841.jpg","position":"bottom","size":"cover"}}}' Response {"payment_id":"pay_Gw2avLXsTOJUSvESS1ig","merchant_id":"merchant_1743758708","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_Gw2avLXsTOJUSvESS1ig_secret_XthFTGPAmHOvIG4wf0lf","created":"2025-04-07T10:12:36.809Z","currency":"EUR","customer_id":"cus_9SCrW9x19m2WbGYHprJS","customer":{"id":"cus_9SCrW9x19m2WbGYHprJS","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"NL","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_9SCrW9x19m2WbGYHprJS","created_at":1744020756,"expires":1744024356,"secret":"epk_4baa462e06a34161875cda39626e0612"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1743758708/pay_Gw2avLXsTOJUSvESS1ig?locale=en","secure_link":"http://localhost:8080/payment_link/s/merchant_1743758708/pay_Gw2avLXsTOJUSvESS1ig?locale=en","payment_link_id":"plink_kN6v8N8kffrl3cdX3sf7"},"profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-07T10:27:36.806Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-07T10:12:36.831Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"issuer_error_code":null,"issuer_error_message":null} Verify below things 1. Payment journey is as expected </details> <details> <summary>3. Give improper data for the text fields to be rendered in transaction_details</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_ML2p8kRGcMvi4oQ3cPnIfz5R2rO31efjWKXzgMnbRCnj5pUpjiki8K2HONlmMAb4' \ --data-raw '{"authentication_type":"three_ds","customer_id":"cus_9SCrW9x19m2WbGYHprJS","profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","amount":100,"currency":"EUR","payment_link":true,"setup_future_usage":"off_session","capture_method":"automatic","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"NL","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"return_url":"https://example.com","payment_link_config":{"theme":"#003264","skip_status_screen":true,"transaction_details":[{"key":"a","value":"<script href=\"https://www.somesite.com\"></script>","ui_configuration":{"is_key_bold":true,"is_value_bold":true}}],"background_image":{"url":"https://img.freepik.com/free-photo/abstract-blue-geometric-shapes-background_24972-1841.jpg","position":"bottom","size":"cover"}}}' Response {"payment_id":"pay_U31G1jOtO9PLlEAhaCnh","merchant_id":"merchant_1743758708","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_U31G1jOtO9PLlEAhaCnh_secret_pdVAtxEgm8M2EXyvQekZ","created":"2025-04-07T10:13:54.256Z","currency":"EUR","customer_id":"cus_9SCrW9x19m2WbGYHprJS","customer":{"id":"cus_9SCrW9x19m2WbGYHprJS","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"NL","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_9SCrW9x19m2WbGYHprJS","created_at":1744020834,"expires":1744024434,"secret":"epk_4e5e8c040ef24d22841731b62003d0cb"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1743758708/pay_U31G1jOtO9PLlEAhaCnh?locale=en","secure_link":"http://localhost:8080/payment_link/s/merchant_1743758708/pay_U31G1jOtO9PLlEAhaCnh?locale=en","payment_link_id":"plink_PH1XXvtv2yl3N9Kh9It8"},"profile_id":"pro_jZ4ix0hYxn8qi2NSSYih","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-04-07T10:28:54.250Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-04-07T10:13:54.276Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"issuer_error_code":null,"issuer_error_message":null} Verify below things 1. Giving any malformed script or any other tags in `transaction_details` renders it as a text <img width="658" alt="Screenshot 2025-04-07 at 3 44 37 PM" src="https://github.com/user-attachments/assets/973c69d4-c429-45af-9d06-9559faffca26" /> </details> ## 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.114.0
4ad0492a88ec2c53b9c70af9a999fc3127c19345
4ad0492a88ec2c53b9c70af9a999fc3127c19345
juspay/hyperswitch
juspay__hyperswitch-7679
Bug: Modify Openspec API for updating API Reference Doc with the updated auth Update the Openspec API, to use the latest API Key auth for profiles and mca routes.
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 65c713eb7f5..64be4ebc3cc 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -1760,7 +1760,7 @@ }, "security": [ { - "admin_api_key": [] + "api_key": [] } ] }, @@ -1805,7 +1805,7 @@ }, "security": [ { - "admin_api_key": [] + "api_key": [] } ] } @@ -1859,7 +1859,7 @@ }, "security": [ { - "admin_api_key": [] + "api_key": [] } ] }, @@ -1940,7 +1940,7 @@ }, "security": [ { - "admin_api_key": [] + "api_key": [] } ] }, @@ -3122,7 +3122,7 @@ }, "security": [ { - "admin_api_key": [] + "api_key": [] } ] }, @@ -3211,7 +3211,7 @@ }, "security": [ { - "admin_api_key": [] + "api_key": [] } ] }, @@ -3276,7 +3276,7 @@ }, "security": [ { - "admin_api_key": [] + "api_key": [] } ] }, diff --git a/crates/openapi/src/routes/merchant_connector_account.rs b/crates/openapi/src/routes/merchant_connector_account.rs index 372f8688a26..9a205abb1a2 100644 --- a/crates/openapi/src/routes/merchant_connector_account.rs +++ b/crates/openapi/src/routes/merchant_connector_account.rs @@ -57,7 +57,7 @@ ), tag = "Merchant Connector Account", operation_id = "Create a Merchant Connector", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn connector_create() {} @@ -142,7 +142,7 @@ pub async fn connector_create() {} ), tag = "Merchant Connector Account", operation_id = "Retrieve a Merchant Connector", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn connector_retrieve() {} @@ -183,7 +183,7 @@ pub async fn connector_retrieve() {} ), tag = "Merchant Connector Account", operation_id = "List all Merchant Connectors", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn connector_list() {} @@ -231,7 +231,7 @@ pub async fn connector_list() {} ), tag = "Merchant Connector Account", operation_id = "Update a Merchant Connector", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn connector_update() {} diff --git a/crates/openapi/src/routes/profile.rs b/crates/openapi/src/routes/profile.rs index cc484aa3f95..2b72375f988 100644 --- a/crates/openapi/src/routes/profile.rs +++ b/crates/openapi/src/routes/profile.rs @@ -33,7 +33,7 @@ ), tag = "Profile", operation_id = "Create A Profile", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn profile_create() {} @@ -65,7 +65,7 @@ pub async fn profile_create() {} ), tag = "Profile", operation_id = "Update a Profile", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn profile_update() {} @@ -86,7 +86,7 @@ pub async fn profile_update() {} ), tag = "Profile", operation_id = "Retrieve a Profile", - security(("admin_api_key" = [])) + security(("api_key" = [])) )] pub async fn profile_retrieve() {}
2025-04-01T11:40:04Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Modified the authentication for profile and mca routes to use API Key instead of Admin API Key. This PR has the corresponding OpenAPI spec changes. ### 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)? --> Cannot test Corresponding code changes are there in this PR: [https://github.com/juspay/hyperswitch/pull/7656](https://github.com/juspay/hyperswitch/pull/7656) ## 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.113.0
1100dcc6053990cf832c00cf29db700d77f78480
1100dcc6053990cf832c00cf29db700d77f78480
juspay/hyperswitch
juspay__hyperswitch-7673
Bug: refactor(ci): map respective error messages for `Stripe` `Sofort` Bank Transfers The `Stripe` payment processor has deprecated the `Sofort` Bank Transfer Payment Method. Map the relevant error codes and messages in the cypress test cases.
2025-04-01T07:41:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> Mapping `status`, `error_code`, and `error_message` for `Stripe` Payment Processor `Sofort` Bank Transfer Payment Method as `Sofort` has been deprecated by `Stripe`. ### 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). --> `Stripe` Payment Processor has deprecated `Sofort` Bank Transfer Payment Method. ## 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)? --> ![image](https://github.com/user-attachments/assets/bc3de0de-13ad-4609-85ae-84b67bb2473f) ## 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.113.0
c6078c5827907ee4315c533b5f729607c1c4e3cd
c6078c5827907ee4315c533b5f729607c1c4e3cd
juspay/hyperswitch
juspay__hyperswitch-7669
Bug: Update API Collection Docs Need to update the API Collection present on the website, to use API Key instead of AdminAPI Key. cc: @gorakhnathy7
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 8ce45e57a5a..7d364fa972c 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -3324,7 +3324,7 @@ }, "security": [ { - "api_key": [] + "admin_api_key": [] } ] } diff --git a/crates/openapi/src/routes/profile.rs b/crates/openapi/src/routes/profile.rs index 2b72375f988..e2dfffa2d1f 100644 --- a/crates/openapi/src/routes/profile.rs +++ b/crates/openapi/src/routes/profile.rs @@ -108,7 +108,7 @@ pub async fn profile_retrieve() {} ), tag = "Profile", operation_id = "Delete the Profile", - security(("api_key" = [])) + security(("admin_api_key" = [])) )] pub async fn profile_delete() {}
2025-04-02T09:16:22Z
## 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 --> Need to update the API doc to display Admin API Key instead of API key for Profile - Delete. ### 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). --> Correct Information to be displayed in the API docs. ## 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)? --> Cannot be tested. ## 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.113.0
cfe226943dc5b473e88b7830c54ac73a943ba04b
cfe226943dc5b473e88b7830c54ac73a943ba04b
juspay/hyperswitch
juspay__hyperswitch-7676
Bug: [BUG] Novalnet connector integration ### Bug Description Novalnet's connector response for refunds expects below format ``` pub struct NovalnetRefundResponse { pub customer: Option<NovalnetResponseCustomer>, pub merchant: Option<NovalnetResponseMerchant>, pub result: ResultData, pub transaction: Option<NovalnetRefundsTransactionData>, } pub struct NovalnetRefundsTransactionData { pub amount: Option<u64>, pub date: Option<String>, pub currency: Option<common_enums::Currency>, pub order_no: Option<String>, pub payment_type: String, pub refund: RefundData, pub refunded_amount: u64, pub status: NovalnetTransactionStatus, pub status_code: u64, pub test_mode: u8, pub tid: Option<Secret<i64>>, } pub struct RefundData { amount: u64, currency: common_enums::Currency, payment_type: String, tid: Option<Secret<i64>>, } ``` Which fails at deserialization for a specific case. ``` { "result": { "status": "FAILURE", "status_code": 300079, "status_text": "Refund limit exceeded. Please contact our support department at [email protected]" }, "transaction": { "amount": 123, "currency": "EUR", "order_no": "pay_be68heac90b_1", "payment_type": "CREDITCARD", "refund": { "amount": 123, "currency": "EUR" }, "status": "CONFIRMED", "status_code": 100, "test_mode": 0, "tid": 2187482476274382 } } ``` Under `RefundData` object, `payment_type` is made as a required parameter which is missing in the response for certain scenarios leading to keeping the refund in a PENDING state. ### Expected Behavior Deserialization should not fail and mark the refund status as PENDING ### Actual Behavior Deserialization should succeed and mark the refund status to FAILURE in such scenarios. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index e35384659d1..2a8b0911dca 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -902,7 +902,7 @@ pub struct NovalnetRefundsTransactionData { pub order_no: Option<String>, pub payment_type: String, pub refund: RefundData, - pub refunded_amount: u64, + pub refunded_amount: Option<u64>, pub status: NovalnetTransactionStatus, pub status_code: u64, pub test_mode: u8, @@ -913,7 +913,7 @@ pub struct NovalnetRefundsTransactionData { pub struct RefundData { amount: u64, currency: common_enums::Currency, - payment_type: String, + payment_type: Option<String>, tid: Option<Secret<i64>>, }
2025-04-04T11:02:09Z
## 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 --> Need to make unused fields in novalnet refund response as optional. This will prevent the deserialization errors. It's a configuration done on Novalnet side, only available in prod. Cannot test this specific case in sandbox. cc: @kashif-m ### 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). --> Few fields which are not mandatory in response were made mandatory in the types defined which were causing deserialization when parsing connector refund response. ## 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 test: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_LGJYQwEIgppbYvbIuwmQYyHGtMLquJJUujSrP34trbI4k1nnTs1ZyqkG1aI6Nx5N' \ --data '{ "payment_id": "pay_ahzKGIpLrLjWUsalTs0D", "amount": 10000, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ## 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.113.0
bd32dd4f0f259336f004a2358a7771652a3c6689
bd32dd4f0f259336f004a2358a7771652a3c6689
juspay/hyperswitch
juspay__hyperswitch-7668
Bug: Update Postman Collection Need to update the Postman Collection for all the connectors, to use API Key instead of AdminAPI Key, to avoid throwing errors on Jenkins Pipeline.
diff --git a/postman/collection-dir/aci/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/aci/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 2898675c1f2..39bc76dc5f7 100644 --- a/postman/collection-dir/aci/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/aci/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 60c38c826af..9422cfc60d0 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json index e4b52afd7ca..351a1e5facb 100644 --- a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json +++ b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payout Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/airwallex/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/airwallex/Flow Testcases/QuickStart/Payment Connector - Create/request.json index c3696696ddf..bfb34b5f81f 100644 --- a/postman/collection-dir/airwallex/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/airwallex/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/authorizedotnet/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 2570bc3f1d5..9a7056a3458 100644 --- a/postman/collection-dir/authorizedotnet/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/authorizedotnet/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/request.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/request.json index 3ea447df397..e5ae7c9bc42 100644 --- a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/request.json +++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bambora/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/bambora/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 83c58bd9680..a5e94d7fd8c 100644 --- a/postman/collection-dir/bambora/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/bambora/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bambora_3ds/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/bambora_3ds/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 83c58bd9680..a5e94d7fd8c 100644 --- a/postman/collection-dir/bambora_3ds/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/bambora_3ds/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bankofamerica/API Key/.meta.json b/postman/collection-dir/bankofamerica/API Key/.meta.json index 0388c2d61b4..bad437ba719 100644 --- a/postman/collection-dir/bankofamerica/API Key/.meta.json +++ b/postman/collection-dir/bankofamerica/API Key/.meta.json @@ -3,7 +3,6 @@ "Create API Key", "Update API Key", "Retrieve API Key", - "List API Keys", - "Delete API Key" + "List API Keys" ] } diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index cc19ac2bab2..8d3a6dd36e0 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -48,8 +48,8 @@ "payment_method_data": { "card": { "card_number": "4242424242424242", - "card_exp_month": "01", - "card_exp_year": "24", + "card_exp_month": "10", + "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json index 14f671d7f6f..320472d2566 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json @@ -40,8 +40,8 @@ "payment_method_data": { "card": { "card_number": "4242424242424242", - "card_exp_month": "01", - "card_exp_year": "24", + "card_exp_month": "10", + "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/QuickStart/Payment Connector - Create/request.json index f47c4f9d3bb..b8ea1c556dd 100644 --- a/postman/collection-dir/bankofamerica/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/bankofamerica/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bankofamerica/PaymentConnectors/.meta.json b/postman/collection-dir/bankofamerica/PaymentConnectors/.meta.json index 3f8bc360dd4..6d68eeab4ab 100644 --- a/postman/collection-dir/bankofamerica/PaymentConnectors/.meta.json +++ b/postman/collection-dir/bankofamerica/PaymentConnectors/.meta.json @@ -5,6 +5,7 @@ "Payment Connector - Update", "List Connectors by MID", "Payment Connector - Delete", - "Merchant Account - Delete" + "Merchant Account - Delete", + "Delete API Key" ] } diff --git a/postman/collection-dir/bankofamerica/API Key/Delete API Key/.event.meta.json b/postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/.event.meta.json similarity index 100% rename from postman/collection-dir/bankofamerica/API Key/Delete API Key/.event.meta.json rename to postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/.event.meta.json diff --git a/postman/collection-dir/bankofamerica/API Key/Delete API Key/event.test.js b/postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/event.test.js similarity index 100% rename from postman/collection-dir/bankofamerica/API Key/Delete API Key/event.test.js rename to postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/event.test.js diff --git a/postman/collection-dir/bankofamerica/API Key/Delete API Key/request.json b/postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/request.json similarity index 100% rename from postman/collection-dir/bankofamerica/API Key/Delete API Key/request.json rename to postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/request.json diff --git a/postman/collection-dir/bankofamerica/API Key/Delete API Key/response.json b/postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/response.json similarity index 100% rename from postman/collection-dir/bankofamerica/API Key/Delete API Key/response.json rename to postman/collection-dir/bankofamerica/PaymentConnectors/Delete API Key/response.json diff --git a/postman/collection-dir/bankofamerica/PaymentConnectors/List Connectors by MID/request.json b/postman/collection-dir/bankofamerica/PaymentConnectors/List Connectors by MID/request.json index 89aa4e59406..0ae1fe13e0a 100644 --- a/postman/collection-dir/bankofamerica/PaymentConnectors/List Connectors by MID/request.json +++ b/postman/collection-dir/bankofamerica/PaymentConnectors/List Connectors by MID/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Create/request.json b/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Create/request.json index f47c4f9d3bb..b8ea1c556dd 100644 --- a/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Create/request.json +++ b/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Retrieve/request.json b/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Retrieve/request.json index b87e6538125..bf901d6b467 100644 --- a/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Retrieve/request.json +++ b/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Retrieve/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Update/request.json b/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Update/request.json index db33632a3ad..a3d3b6b9189 100644 --- a/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Update/request.json +++ b/postman/collection-dir/bankofamerica/PaymentConnectors/Payment Connector - Update/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/bluesnap/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/bluesnap/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 572a23fd7a2..2b58056d193 100644 --- a/postman/collection-dir/bluesnap/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/bluesnap/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/braintree/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/braintree/Flow Testcases/QuickStart/Payment Connector - Create/request.json index b65988d0f19..94a18d71e90 100644 --- a/postman/collection-dir/braintree/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/braintree/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 68f12ba04e1..a9b14b69df7 100644 --- a/postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 35bf67cdd4e..8971181613d 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/forte/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/forte/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 9ad21398b73..c8699219e41 100644 --- a/postman/collection-dir/forte/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/forte/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/globalpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/globalpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 89739480aa8..1d02bdf748d 100644 --- a/postman/collection-dir/globalpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/globalpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/hyperswitch/API Key/.meta.json b/postman/collection-dir/hyperswitch/API Key/.meta.json index 0388c2d61b4..bad437ba719 100644 --- a/postman/collection-dir/hyperswitch/API Key/.meta.json +++ b/postman/collection-dir/hyperswitch/API Key/.meta.json @@ -3,7 +3,6 @@ "Create API Key", "Update API Key", "Retrieve API Key", - "List API Keys", - "Delete API Key" + "List API Keys" ] } diff --git a/postman/collection-dir/hyperswitch/Hackathon/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/hyperswitch/Hackathon/QuickStart/Payment Connector - Create/request.json index 29cf7b13b01..f4ab0deef92 100644 --- a/postman/collection-dir/hyperswitch/Hackathon/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/hyperswitch/Hackathon/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/hyperswitch/PaymentConnectors/.meta.json b/postman/collection-dir/hyperswitch/PaymentConnectors/.meta.json index 3f8bc360dd4..6d68eeab4ab 100644 --- a/postman/collection-dir/hyperswitch/PaymentConnectors/.meta.json +++ b/postman/collection-dir/hyperswitch/PaymentConnectors/.meta.json @@ -5,6 +5,7 @@ "Payment Connector - Update", "List Connectors by MID", "Payment Connector - Delete", - "Merchant Account - Delete" + "Merchant Account - Delete", + "Delete API Key" ] } diff --git a/postman/collection-dir/hyperswitch/API Key/Delete API Key/.event.meta.json b/postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/.event.meta.json similarity index 100% rename from postman/collection-dir/hyperswitch/API Key/Delete API Key/.event.meta.json rename to postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/.event.meta.json diff --git a/postman/collection-dir/hyperswitch/API Key/Delete API Key/event.test.js b/postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/event.test.js similarity index 100% rename from postman/collection-dir/hyperswitch/API Key/Delete API Key/event.test.js rename to postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/event.test.js diff --git a/postman/collection-dir/hyperswitch/API Key/Delete API Key/request.json b/postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/request.json similarity index 100% rename from postman/collection-dir/hyperswitch/API Key/Delete API Key/request.json rename to postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/request.json diff --git a/postman/collection-dir/hyperswitch/API Key/Delete API Key/response.json b/postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/response.json similarity index 100% rename from postman/collection-dir/hyperswitch/API Key/Delete API Key/response.json rename to postman/collection-dir/hyperswitch/PaymentConnectors/Delete API Key/response.json diff --git a/postman/collection-dir/hyperswitch/PaymentConnectors/List Connectors by MID/request.json b/postman/collection-dir/hyperswitch/PaymentConnectors/List Connectors by MID/request.json index 81d0ea5ef1e..f731ff3a422 100644 --- a/postman/collection-dir/hyperswitch/PaymentConnectors/List Connectors by MID/request.json +++ b/postman/collection-dir/hyperswitch/PaymentConnectors/List Connectors by MID/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Create/request.json b/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Create/request.json index 38cf4e46f2e..3b12122e568 100644 --- a/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Create/request.json +++ b/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Retrieve/request.json b/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Retrieve/request.json index 7536380bcf0..05f84b5771e 100644 --- a/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Retrieve/request.json +++ b/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Retrieve/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Update/request.json b/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Update/request.json index 9deb9f0addc..4cd08383649 100644 --- a/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Update/request.json +++ b/postman/collection-dir/hyperswitch/PaymentConnectors/Payment Connector - Update/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/hyperswitch/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/hyperswitch/QuickStart/Payment Connector - Create/request.json index 29cf7b13b01..f4ab0deef92 100644 --- a/postman/collection-dir/hyperswitch/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/hyperswitch/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/mollie/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/mollie/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 4f209de9030..dee607ae12a 100644 --- a/postman/collection-dir/mollie/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/mollie/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/multisafepay/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/multisafepay/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 1385e967bbd..317065ac581 100644 --- a/postman/collection-dir/multisafepay/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/multisafepay/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario6- Create payment with Invalid Merchant ID/Payment Connector - Update/request.json b/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario6- Create payment with Invalid Merchant ID/Payment Connector - Update/request.json index eb5a39cc56c..de7f5dfeebd 100644 --- a/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario6- Create payment with Invalid Merchant ID/Payment Connector - Update/request.json +++ b/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario6- Create payment with Invalid Merchant ID/Payment Connector - Update/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/nexinets/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/nexinets/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 4928ee1d4bd..a1a6e69049d 100644 --- a/postman/collection-dir/nexinets/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/nexinets/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/nmi/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 23629d0fa75..fee1cb79ce5 100644 --- a/postman/collection-dir/nmi/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 32e3afc6348..db7adca82fe 100644 --- a/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/nuvei/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/payme/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/payme/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 71463f2446f..b7ba97dc3ea 100644 --- a/postman/collection-dir/payme/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/payme/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/paypal/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/paypal/Flow Testcases/QuickStart/Payment Connector - Create/request.json index cdcee289022..583b419632a 100644 --- a/postman/collection-dir/paypal/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/paypal/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/powertranz/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/powertranz/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 3b60b0db2e4..e6fb6924ae6 100644 --- a/postman/collection-dir/powertranz/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/powertranz/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/prophetpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/prophetpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json index fd47c40ce19..936435de29c 100644 --- a/postman/collection-dir/prophetpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/prophetpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/rapyd/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/rapyd/Flow Testcases/QuickStart/Payment Connector - Create/request.json index d19329121f5..ae74abf20ab 100644 --- a/postman/collection-dir/rapyd/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/rapyd/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/shift4/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/shift4/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 9b7f48dca22..a9321943c5d 100644 --- a/postman/collection-dir/shift4/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/shift4/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/API Key/.meta.json b/postman/collection-dir/stripe/API Key/.meta.json index 0388c2d61b4..bad437ba719 100644 --- a/postman/collection-dir/stripe/API Key/.meta.json +++ b/postman/collection-dir/stripe/API Key/.meta.json @@ -3,7 +3,6 @@ "Create API Key", "Update API Key", "Retrieve API Key", - "List API Keys", - "Delete API Key" + "List API Keys" ] } diff --git a/postman/collection-dir/stripe/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 140ececab9a..2922d5654c0 100644 --- a/postman/collection-dir/stripe/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/PaymentConnectors/.meta.json b/postman/collection-dir/stripe/PaymentConnectors/.meta.json index 3f8bc360dd4..6d68eeab4ab 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/.meta.json +++ b/postman/collection-dir/stripe/PaymentConnectors/.meta.json @@ -5,6 +5,7 @@ "Payment Connector - Update", "List Connectors by MID", "Payment Connector - Delete", - "Merchant Account - Delete" + "Merchant Account - Delete", + "Delete API Key" ] } diff --git a/postman/collection-dir/stripe/API Key/Delete API Key/.event.meta.json b/postman/collection-dir/stripe/PaymentConnectors/Delete API Key/.event.meta.json similarity index 100% rename from postman/collection-dir/stripe/API Key/Delete API Key/.event.meta.json rename to postman/collection-dir/stripe/PaymentConnectors/Delete API Key/.event.meta.json diff --git a/postman/collection-dir/stripe/API Key/Delete API Key/event.test.js b/postman/collection-dir/stripe/PaymentConnectors/Delete API Key/event.test.js similarity index 100% rename from postman/collection-dir/stripe/API Key/Delete API Key/event.test.js rename to postman/collection-dir/stripe/PaymentConnectors/Delete API Key/event.test.js diff --git a/postman/collection-dir/stripe/API Key/Delete API Key/request.json b/postman/collection-dir/stripe/PaymentConnectors/Delete API Key/request.json similarity index 100% rename from postman/collection-dir/stripe/API Key/Delete API Key/request.json rename to postman/collection-dir/stripe/PaymentConnectors/Delete API Key/request.json diff --git a/postman/collection-dir/stripe/API Key/Delete API Key/response.json b/postman/collection-dir/stripe/PaymentConnectors/Delete API Key/response.json similarity index 100% rename from postman/collection-dir/stripe/API Key/Delete API Key/response.json rename to postman/collection-dir/stripe/PaymentConnectors/Delete API Key/response.json diff --git a/postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json b/postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json index e3ed8ab2925..637e403e782 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json +++ b/postman/collection-dir/stripe/PaymentConnectors/List Connectors by MID/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create First Connector/request.json b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create First Connector/request.json index 1e810266994..afe396aa8f1 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create First Connector/request.json +++ b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create First Connector/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create Second Connector/request.json b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create Second Connector/request.json index f88a293e6ad..f2da67aa6f4 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create Second Connector/request.json +++ b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create Multiple/Create Second Connector/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create/request.json b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create/request.json index bb5f920fc50..ef06cfc1cc4 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create/request.json +++ b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json index 97afd9f26e7..d592bad50f6 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json +++ b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Retrieve/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json index f9631103356..31a26118750 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json +++ b/postman/collection-dir/stripe/PaymentConnectors/Payment Connector - Update/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/stripe/QuickStart/Payment Connector - Create/request.json index 658889d26dc..af8ae95c3e9 100644 --- a/postman/collection-dir/stripe/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/stripe/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json b/postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json index 84c7a2fa48c..980c77b8515 100644 --- a/postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json +++ b/postman/collection-dir/stripe/QuickStart/Payment Connector - Update/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json index b6c15ab9af2..77bf15bf889 100644 --- a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 532d3672d7e..e99e7a249a8 100644 --- a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/wise/Flow Testcases/QuickStart/Payout Connector - Create/request.json b/postman/collection-dir/wise/Flow Testcases/QuickStart/Payout Connector - Create/request.json index 6b4757c18c3..9b3725fe8ad 100644 --- a/postman/collection-dir/wise/Flow Testcases/QuickStart/Payout Connector - Create/request.json +++ b/postman/collection-dir/wise/Flow Testcases/QuickStart/Payout Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/worldline/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/worldline/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 4225d477936..aa161413fd5 100644 --- a/postman/collection-dir/worldline/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/worldline/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/zen/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/zen/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 4a2d34a4aa9..58766c99271 100644 --- a/postman/collection-dir/zen/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/zen/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, { diff --git a/postman/collection-dir/zsl/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/zsl/Flow Testcases/QuickStart/Payment Connector - Create/request.json index db15acdaaee..8ee4d78ae89 100644 --- a/postman/collection-dir/zsl/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/zsl/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -4,7 +4,7 @@ "apikey": [ { "key": "value", - "value": "{{admin_api_key}}", + "value": "{{api_key}}", "type": "string" }, {
2025-04-02T10:04:20Z
## 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 --> Modified the Auth in the postman collection for payment connectors, from Admin API Key to API Key. ### 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). --> Ensure proper testing for the Payment Connector APIs. ## 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)? --> ### Stripe <img width="1191" alt="Screenshot 2025-04-02 at 5 04 26 PM" src="https://github.com/user-attachments/assets/29c5b2a7-bd54-42e1-907b-827927379f17" /> <img width="992" alt="image" src="https://github.com/user-attachments/assets/e7dc40b0-ddde-4c8d-bd5b-8496278d966e" /> ### Bankofamerica <img width="1197" alt="image" src="https://github.com/user-attachments/assets/f6b1526a-ac1d-4ef1-9e12-e8f92ba84229" /> <img width="1171" alt="image" src="https://github.com/user-attachments/assets/8c8f686d-cab5-4e82-af6b-77eb15a4f76b" /> ### Hyperswitch <img width="1214" alt="image" src="https://github.com/user-attachments/assets/a96a79c8-f16c-47bc-8367-2d92e1aef5e4" /> <img width="984" alt="image" src="https://github.com/user-attachments/assets/19306109-9c27-40fc-a6a6-8bd757a2c40e" /> ## 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.113.0
b8f66155d4a23c10f129591994a8a30715375b87
b8f66155d4a23c10f129591994a8a30715375b87
juspay/hyperswitch
juspay__hyperswitch-7664
Bug: Modify profile and merchant_connector_account routes to use `ApiKeyAuthWithMerchantIdFromRoute` auth Hotfix Description: Currently, the following routes use AdminApiAuthWithMerchantIdFromRoute for authentication: Profile Create, Retrieve, Update Merchant Connector Account Create, List, Retrieve, Update This has to be updated to a more appropriate auth layer: ApiKeyAuthWithMerchantIdFromRoute, which validates that the merchant_id in the API key matches the one in the route.
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 3cd959838a5..1c494542228 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -499,7 +499,7 @@ pub async fn connector_create( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ProfileConnectorWrite, @@ -598,7 +598,7 @@ pub async fn connector_retrieve( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be ProfileConnectorRead, but since this API responds with @@ -716,7 +716,7 @@ pub async fn connector_list( merchant_id.to_owned(), |state, _auth, merchant_id, _| list_payment_connectors(state, merchant_id, None), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorRead, @@ -769,7 +769,7 @@ pub async fn connector_list_profile( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::ProfileConnectorRead, @@ -830,7 +830,7 @@ pub async fn connector_update( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ProfileConnectorWrite, diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rs index 1b98160546d..cd91275df71 100644 --- a/crates/router/src/routes/profiles.rs +++ b/crates/router/src/routes/profiles.rs @@ -29,7 +29,7 @@ pub async fn profile_create( create_profile(state, req, auth_data.merchant_account, auth_data.key_store) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountWrite, @@ -95,7 +95,7 @@ pub async fn profile_retrieve( profile_id, |state, auth_data, profile_id, _| retrieve_profile(state, profile_id, auth_data.key_store), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: permissions::Permission::ProfileAccountRead, @@ -158,7 +158,7 @@ pub async fn profile_update( json_payload.into_inner(), |state, auth_data, req, _| update_profile(state, &profile_id, auth_data.key_store, req), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantAndProfileFromRoute { merchant_id: merchant_id.clone(), profile_id: profile_id.clone(), @@ -243,7 +243,7 @@ pub async fn profiles_list( merchant_id.clone(), |state, _auth, merchant_id, _| list_profile(state, merchant_id, None), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountRead, @@ -309,7 +309,7 @@ pub async fn profiles_list_at_profile_level( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::ProfileAccountRead, @@ -402,7 +402,7 @@ pub async fn payment_connector_list_profile( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::ProfileConnectorRead, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 4eb91756661..7e3d6802b88 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -633,6 +633,137 @@ where } } +#[derive(Debug)] +pub struct ApiKeyAuthWithMerchantIdFromRoute(pub id_type::MerchantId); + +#[cfg(feature = "partial-auth")] +impl GetAuthType for ApiKeyAuthWithMerchantIdFromRoute { + fn get_auth_type(&self) -> detached::PayloadType { + detached::PayloadType::ApiKey + } +} + +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuthWithMerchantIdFromRoute +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let merchant_id_from_route = self.0.clone(); + let api_key = get_api_key(request_headers) + .change_context(errors::ApiErrorResponse::Unauthorized)? + .trim(); + if api_key.is_empty() { + return Err(errors::ApiErrorResponse::Unauthorized) + .attach_printable("API key is empty"); + } + + let api_key = api_keys::PlaintextApiKey::from(api_key); + let hash_key = { + let config = state.conf(); + config.api_keys.get_inner().get_hash_key()? + }; + let hashed_api_key = api_key.keyed_hash(hash_key.peek()); + + let stored_api_key = state + .store() + .find_api_key_by_hash_optional(hashed_api_key.into()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed + .attach_printable("Failed to retrieve API key")? + .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` + .attach_printable("Merchant not authenticated")?; + + if stored_api_key + .expires_at + .map(|expires_at| expires_at < date_time::now()) + .unwrap_or(false) + { + return Err(report!(errors::ApiErrorResponse::Unauthorized)) + .attach_printable("API key has expired"); + } + + let key_manager_state = &(&state.session_state()).into(); + + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &stored_api_key.merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Failed to fetch merchant key store for the merchant id")?; + + let profile_id = + get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)? + .map(id_type::ProfileId::from_str) + .transpose() + .change_context(errors::ValidationError::IncorrectValueProvided { + field_name: "X-Profile-Id", + }) + .change_context(errors::ApiErrorResponse::Unauthorized)?; + + if merchant_id_from_route != stored_api_key.merchant_id { + return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( + "Merchant ID from route and Merchant ID from api-key in header do not match", + ); + } + + let merchant = state + .store() + .find_merchant_account_by_merchant_id( + key_manager_state, + &stored_api_key.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account + let (merchant, platform_merchant_account) = if state.conf().platform.enabled { + get_platform_merchant_account(state, request_headers, merchant).await? + } else { + (merchant, None) + }; + + let key_store = if platform_merchant_account.is_some() { + state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant.get_id(), + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Failed to fetch merchant key store for the merchant id")? + } else { + key_store + }; + + let auth = AuthenticationData { + merchant_account: merchant, + platform_merchant_account, + key_store, + profile_id, + }; + Ok(( + auth.clone(), + AuthenticationType::ApiKey { + merchant_id: auth.merchant_account.get_id().clone(), + key_id: stored_api_key.key_id, + }, + )) + } +} + #[cfg(not(feature = "partial-auth"))] #[async_trait] impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I> diff --git a/cypress-tests-v2/cypress/support/commands.js b/cypress-tests-v2/cypress/support/commands.js index b6955c542a7..33f8907ce3f 100644 --- a/cypress-tests-v2/cypress/support/commands.js +++ b/cypress-tests-v2/cypress/support/commands.js @@ -310,7 +310,7 @@ Cypress.Commands.add( "businessProfileCreateCall", (businessProfileCreateBody, globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("adminApiKey"); + const api_key = globalState.get("apiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const url = `${base_url}/v2/profiles`; @@ -353,7 +353,7 @@ Cypress.Commands.add( ); Cypress.Commands.add("businessProfileRetrieveCall", (globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("adminApiKey"); + const api_key = globalState.get("apiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId"); @@ -395,7 +395,7 @@ Cypress.Commands.add( "businessProfileUpdateCall", (businessProfileUpdateBody, globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("adminApiKey"); + const api_key = globalState.get("apiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId");
2025-03-28T09:12:40Z
## 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 --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7656](https://github.com/juspay/hyperswitch/pull/7656) ### 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.113.0
df7daa611e069e027fbef90fd8d17e53a28d7580
df7daa611e069e027fbef90fd8d17e53a28d7580
juspay/hyperswitch
juspay__hyperswitch-7658
Bug: Modify profile and merchant_connector_account routes to use `ApiKeyAuthWithMerchantIdFromRoute` auth ### Description: Currently, the following routes use `AdminApiAuthWithMerchantIdFromRoute` for authentication: - Profile Create, Retrieve, Update - Merchant Connector Account Create, List, Retrieve, Update This has to be updated to a more appropriate auth layer: `ApiKeyAuthWithMerchantIdFromRoute`, which validates that the `merchant_id` in the API key matches the one in the route.
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 3cd959838a5..1c494542228 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -499,7 +499,7 @@ pub async fn connector_create( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ProfileConnectorWrite, @@ -598,7 +598,7 @@ pub async fn connector_retrieve( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, // This should ideally be ProfileConnectorRead, but since this API responds with @@ -716,7 +716,7 @@ pub async fn connector_list( merchant_id.to_owned(), |state, _auth, merchant_id, _| list_payment_connectors(state, merchant_id, None), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorRead, @@ -769,7 +769,7 @@ pub async fn connector_list_profile( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::ProfileConnectorRead, @@ -830,7 +830,7 @@ pub async fn connector_update( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ProfileConnectorWrite, diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rs index 1b98160546d..cd91275df71 100644 --- a/crates/router/src/routes/profiles.rs +++ b/crates/router/src/routes/profiles.rs @@ -29,7 +29,7 @@ pub async fn profile_create( create_profile(state, req, auth_data.merchant_account, auth_data.key_store) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountWrite, @@ -95,7 +95,7 @@ pub async fn profile_retrieve( profile_id, |state, auth_data, profile_id, _| retrieve_profile(state, profile_id, auth_data.key_store), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: permissions::Permission::ProfileAccountRead, @@ -158,7 +158,7 @@ pub async fn profile_update( json_payload.into_inner(), |state, auth_data, req, _| update_profile(state, &profile_id, auth_data.key_store, req), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantAndProfileFromRoute { merchant_id: merchant_id.clone(), profile_id: profile_id.clone(), @@ -243,7 +243,7 @@ pub async fn profiles_list( merchant_id.clone(), |state, _auth, merchant_id, _| list_profile(state, merchant_id, None), auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::MerchantAccountRead, @@ -309,7 +309,7 @@ pub async fn profiles_list_at_profile_level( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::ProfileAccountRead, @@ -402,7 +402,7 @@ pub async fn payment_connector_list_profile( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: permissions::Permission::ProfileConnectorRead, diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 4eb91756661..7e3d6802b88 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -633,6 +633,137 @@ where } } +#[derive(Debug)] +pub struct ApiKeyAuthWithMerchantIdFromRoute(pub id_type::MerchantId); + +#[cfg(feature = "partial-auth")] +impl GetAuthType for ApiKeyAuthWithMerchantIdFromRoute { + fn get_auth_type(&self) -> detached::PayloadType { + detached::PayloadType::ApiKey + } +} + +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuthWithMerchantIdFromRoute +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let merchant_id_from_route = self.0.clone(); + let api_key = get_api_key(request_headers) + .change_context(errors::ApiErrorResponse::Unauthorized)? + .trim(); + if api_key.is_empty() { + return Err(errors::ApiErrorResponse::Unauthorized) + .attach_printable("API key is empty"); + } + + let api_key = api_keys::PlaintextApiKey::from(api_key); + let hash_key = { + let config = state.conf(); + config.api_keys.get_inner().get_hash_key()? + }; + let hashed_api_key = api_key.keyed_hash(hash_key.peek()); + + let stored_api_key = state + .store() + .find_api_key_by_hash_optional(hashed_api_key.into()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed + .attach_printable("Failed to retrieve API key")? + .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` + .attach_printable("Merchant not authenticated")?; + + if stored_api_key + .expires_at + .map(|expires_at| expires_at < date_time::now()) + .unwrap_or(false) + { + return Err(report!(errors::ApiErrorResponse::Unauthorized)) + .attach_printable("API key has expired"); + } + + let key_manager_state = &(&state.session_state()).into(); + + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &stored_api_key.merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Failed to fetch merchant key store for the merchant id")?; + + let profile_id = + get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)? + .map(id_type::ProfileId::from_str) + .transpose() + .change_context(errors::ValidationError::IncorrectValueProvided { + field_name: "X-Profile-Id", + }) + .change_context(errors::ApiErrorResponse::Unauthorized)?; + + if merchant_id_from_route != stored_api_key.merchant_id { + return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( + "Merchant ID from route and Merchant ID from api-key in header do not match", + ); + } + + let merchant = state + .store() + .find_merchant_account_by_merchant_id( + key_manager_state, + &stored_api_key.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + + // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account + let (merchant, platform_merchant_account) = if state.conf().platform.enabled { + get_platform_merchant_account(state, request_headers, merchant).await? + } else { + (merchant, None) + }; + + let key_store = if platform_merchant_account.is_some() { + state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant.get_id(), + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Failed to fetch merchant key store for the merchant id")? + } else { + key_store + }; + + let auth = AuthenticationData { + merchant_account: merchant, + platform_merchant_account, + key_store, + profile_id, + }; + Ok(( + auth.clone(), + AuthenticationType::ApiKey { + merchant_id: auth.merchant_account.get_id().clone(), + key_id: stored_api_key.key_id, + }, + )) + } +} + #[cfg(not(feature = "partial-auth"))] #[async_trait] impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I> diff --git a/cypress-tests-v2/cypress/support/commands.js b/cypress-tests-v2/cypress/support/commands.js index b6955c542a7..33f8907ce3f 100644 --- a/cypress-tests-v2/cypress/support/commands.js +++ b/cypress-tests-v2/cypress/support/commands.js @@ -310,7 +310,7 @@ Cypress.Commands.add( "businessProfileCreateCall", (businessProfileCreateBody, globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("adminApiKey"); + const api_key = globalState.get("apiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const url = `${base_url}/v2/profiles`; @@ -353,7 +353,7 @@ Cypress.Commands.add( ); Cypress.Commands.add("businessProfileRetrieveCall", (globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("adminApiKey"); + const api_key = globalState.get("apiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId"); @@ -395,7 +395,7 @@ Cypress.Commands.add( "businessProfileUpdateCall", (businessProfileUpdateBody, globalState) => { // Define the necessary variables and constants - const api_key = globalState.get("adminApiKey"); + const api_key = globalState.get("apiKey"); const base_url = globalState.get("baseUrl"); const merchant_id = globalState.get("merchantId"); const profile_id = globalState.get("profileId");
2025-03-27T11:52:47Z
## 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 --> Currently, the following routes use `AdminApiAuthWithMerchantIdFromRoute` for authentication: - Profile Create, Retrieve, Update - Merchant Connector Account Create, List, Retrieve, Update This is being updated to a more appropriate auth layer: `ApiKeyAuthWithMerchantIdFromRoute`, which validates that the `merchant_id` in the API key matches the one in the route. ### 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). --> These routes are profile and merchant-specific and can be accessed using the merchant's API key, ## 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)? --> Folowing are the endpoints which are changed: ### Business Profile Create: ```bash curl --location 'http://localhost:8080/account/merchant_1743057601/business_profile' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_5xsUyXxOG9PXQcg3rFHb04PhdadsqtKltGAZ6ABoJBYXNSIqBlOuOouPin0bnvoY' \ --data '{ "profile_name": "final-test" }' ``` ### Business Profile Retrieve: ```bash curl --location 'http://localhost:8080/account/merchant_1743057601/business_profile/pro_DaWH06Gvj0uyHu5TIzo9' \ --header 'api-key: dev_5xsUyXxOG9PXQcg3rFHb04PhdadsqtKltGAZ6ABoJBYXNSIqBlOuOouPin0bnvoY' ``` ### Business Profile Update: ```bash curl --location 'http://localhost:8080/account/merchant_1743057601/business_profile/pro_r4qhkx1sVFsohrVEKuu2' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_5xsUyXxOG9PXQcg3rFHb04PhdadsqtKltGAZ6ABoJBYXNSIqBlOuOouPin0bnvoY' \ --data '{ "profile_name": "test-profile-auth2" }' ``` ### Business Profile List: ```bash curl --location 'http://localhost:8080/account/merchant_1743057601/business_profile' \ --header 'api-key: dev_5xsUyXxOG9PXQcg3rFHb04PhdadsqtKltGAZ6ABoJBYXNSIqBlOuOouPin0bnvoY' ``` ### Merchant Connector Account Create ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' \ --data '{ "connector_type": "payment_processor", "profile_id": "pro_diCodYSThA3xAuDZ2rKV", "connector_name": "paypal_test", "connector_label": "paypal_test_default4", "disabled": false, "test_mode": true, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false } ] } ], "metadata": {}, "connector_account_details": { "api_key": "test_key", "auth_type": "HeaderKey" }, "additional_merchant_data": null, "status": "active", "pm_auth_config": null, "connector_wallets_details": null }' ``` ### Merchant Connector Account Retrieve ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/connectors/mca_zAKHkuRqGOnduBqTHzlO' \ --header 'Accept: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' ``` ### Merchant Connector Account Update ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/connectors/mca_zAKHkuRqGOnduBqTHzlO' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' \ --data '{ "connector_type": "payment_processor", "connector_label": "paypal_test_default2", "disabled": false, "test_mode": true, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false } ] } ], "metadata": {}, "additional_merchant_data": null, "status": "active", "pm_auth_config": null, "connector_wallets_details": null }' ``` ### Merchant Connector Account List: ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/connectors' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' ``` ### Merchant Connector Account Profile List: ```bash curl --location 'http://localhost:8080/account/merchant_1743084798/profile/connectors' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_awg6L6UKmUmNmvnJhYmgZpyWGKW2IfpT3Aq9huE9SicU5HbH0qk95MgQRMrjIdfT' ``` ## 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.113.0
f3d6b15a2ade7dd98fec59777301f44d166f3be3
f3d6b15a2ade7dd98fec59777301f44d166f3be3
juspay/hyperswitch
juspay__hyperswitch-7646
Bug: feat: remove client_secret from payment_intents and update related code Change how client secret is made in Create Payment Intent Old `{Payment_id}_secret_{Secret}` `eg : pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo` New `cs_{Secret}` `eg: cs_0195d2be95ba7ef1a05066e163295562`
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index de2cd1b0360..27936b2917c 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -17102,7 +17102,7 @@ "client_secret": { "type": "string", "description": "It's a token used for client side verification.", - "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo" + "example": "cs_0195b34da95d75239c6a4bf514458896" }, "profile_id": { "type": "string", @@ -17699,7 +17699,6 @@ "status", "amount", "customer_id", - "client_secret", "created" ], "properties": { @@ -17729,10 +17728,6 @@ "example": "stripe", "nullable": true }, - "client_secret": { - "type": "string", - "description": "It's a token used for client side verification." - }, "created": { "type": "string", "format": "date-time", diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 3cfadb0a57c..1a07a18f336 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -480,8 +480,8 @@ pub struct PaymentsIntentResponse { pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. - #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] - pub client_secret: common_utils::types::ClientSecret, + #[schema(value_type = String, example = "cs_0195b34da95d75239c6a4bf514458896")] + pub client_secret: Option<Secret<String>>, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] @@ -5576,10 +5576,6 @@ pub struct PaymentsResponse { #[schema(example = "stripe")] pub connector: Option<String>, - /// It's a token used for client side verification. - #[schema(value_type = String)] - pub client_secret: common_utils::types::ClientSecret, - /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] diff --git a/crates/common_utils/src/id_type/global_id/payment.rs b/crates/common_utils/src/id_type/global_id/payment.rs index 5de836cd486..22ac0d4c0a4 100644 --- a/crates/common_utils/src/id_type/global_id/payment.rs +++ b/crates/common_utils/src/id_type/global_id/payment.rs @@ -28,11 +28,6 @@ impl GlobalPaymentId { Self(global_id) } - /// Generate a new ClientId from self - pub fn generate_client_secret(&self) -> types::ClientSecret { - types::ClientSecret::new(self.clone(), generate_time_ordered_id_without_prefix()) - } - /// Generate the id for revenue recovery Execute PT workflow pub fn get_execute_revenue_recovery_id( &self, diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 11c9b17fae6..b9d245d48ce 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -686,261 +686,6 @@ where } } -#[cfg(feature = "v2")] -pub use client_secret_type::ClientSecret; -#[cfg(feature = "v2")] -mod client_secret_type { - use std::fmt; - - use masking::PeekInterface; - use router_env::logger; - - use super::*; - use crate::id_type; - - /// A domain type that can be used to represent a client secret - /// Client secret is generated for a payment and is used to authenticate the client side api calls - #[derive(Debug, PartialEq, Clone, AsExpression)] - #[diesel(sql_type = sql_types::Text)] - pub struct ClientSecret { - /// The payment id of the payment - pub payment_id: id_type::GlobalPaymentId, - /// The secret string - pub secret: masking::Secret<String>, - } - - impl ClientSecret { - pub(crate) fn get_string_repr(&self) -> String { - format!( - "{}_secret_{}", - self.payment_id.get_string_repr(), - self.secret.peek() - ) - } - - /// Create a new client secret - pub(crate) fn new(payment_id: id_type::GlobalPaymentId, secret: String) -> Self { - Self { - payment_id, - secret: masking::Secret::new(secret), - } - } - } - - impl FromStr for ClientSecret { - type Err = ParsingError; - - fn from_str(str_value: &str) -> Result<Self, Self::Err> { - let (payment_id, secret) = - str_value - .rsplit_once("_secret_") - .ok_or(ParsingError::EncodeError( - "Expected a string in the format '{payment_id}_secret_{secret}'", - ))?; - - let payment_id = id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned())) - .map_err(|err| { - logger::error!(global_payment_id_error=?err); - ParsingError::EncodeError("Error while constructing GlobalPaymentId") - })?; - - Ok(Self { - payment_id, - secret: masking::Secret::new(secret.to_owned()), - }) - } - } - - impl<'de> Deserialize<'de> for ClientSecret { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - struct ClientSecretVisitor; - - impl Visitor<'_> for ClientSecretVisitor { - type Value = ClientSecret; - - fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str("a string in the format '{payment_id}_secret_{secret}'") - } - - fn visit_str<E>(self, value: &str) -> Result<ClientSecret, E> - where - E: serde::de::Error, - { - let (payment_id, secret) = value.rsplit_once("_secret_").ok_or_else(|| { - E::invalid_value( - serde::de::Unexpected::Str(value), - &"a string with '_secret_'", - ) - })?; - - let payment_id = - id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned())) - .map_err(serde::de::Error::custom)?; - - Ok(ClientSecret { - payment_id, - secret: masking::Secret::new(secret.to_owned()), - }) - } - } - - deserializer.deserialize_str(ClientSecretVisitor) - } - } - - impl Serialize for ClientSecret { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: serde::ser::Serializer, - { - serializer.serialize_str(self.get_string_repr().as_str()) - } - } - - impl ToSql<sql_types::Text, diesel::pg::Pg> for ClientSecret - where - String: ToSql<sql_types::Text, diesel::pg::Pg>, - { - fn to_sql<'b>( - &'b self, - out: &mut Output<'b, '_, diesel::pg::Pg>, - ) -> diesel::serialize::Result { - let string_repr = self.get_string_repr(); - <String as ToSql<sql_types::Text, diesel::pg::Pg>>::to_sql( - &string_repr, - &mut out.reborrow(), - ) - } - } - - impl<DB> FromSql<sql_types::Text, DB> for ClientSecret - where - DB: Backend, - String: FromSql<sql_types::Text, DB>, - { - fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> { - let string_repr = String::from_sql(value)?; - let (payment_id, secret) = - string_repr - .rsplit_once("_secret_") - .ok_or(ParsingError::EncodeError( - "Expected a string in the format '{payment_id}_secret_{secret}'", - ))?; - - let payment_id = id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned())) - .map_err(|err| { - logger::error!(global_payment_id_error=?err); - ParsingError::EncodeError("Error while constructing GlobalPaymentId") - })?; - - Ok(Self { - payment_id, - secret: masking::Secret::new(secret.to_owned()), - }) - } - } - - impl<DB> Queryable<sql_types::Text, DB> for ClientSecret - where - DB: Backend, - Self: FromSql<sql_types::Text, DB>, - { - type Row = Self; - - fn build(row: Self::Row) -> deserialize::Result<Self> { - Ok(row) - } - } - crate::impl_serializable_secret_id_type!(ClientSecret); - #[cfg(test)] - mod client_secret_tests { - #![allow(clippy::expect_used)] - #![allow(clippy::unwrap_used)] - - use serde_json; - - use super::*; - use crate::id_type::GlobalPaymentId; - - #[test] - fn test_serialize_client_secret() { - let global_payment_id = "12345_pay_1a961ed9093c48b09781bf8ab17ba6bd"; - let secret = "fc34taHLw1ekPgNh92qr".to_string(); - - let expected_client_secret_string = format!("\"{global_payment_id}_secret_{secret}\""); - - let client_secret1 = ClientSecret { - payment_id: GlobalPaymentId::try_from(Cow::Borrowed(global_payment_id)).unwrap(), - secret: masking::Secret::new(secret), - }; - - let parsed_client_secret = - serde_json::to_string(&client_secret1).expect("Failed to serialize client_secret1"); - - assert_eq!(expected_client_secret_string, parsed_client_secret); - } - - #[test] - fn test_deserialize_client_secret() { - // This is a valid global id - let global_payment_id_str = "12345_pay_1a961ed9093c48b09781bf8ab17ba6bd"; - let secret = "fc34taHLw1ekPgNh92qr".to_string(); - - let valid_payment_global_id = - GlobalPaymentId::try_from(Cow::Borrowed(global_payment_id_str)) - .expect("Failed to create valid global payment id"); - - // This is an invalid global id because of the cell id being in invalid length - let invalid_global_payment_id = "123_pay_1a961ed9093c48b09781bf8ab17ba6bd"; - - // Create a client secret string which is valid - let valid_client_secret = format!(r#""{global_payment_id_str}_secret_{secret}""#); - - dbg!(&valid_client_secret); - - // Create a client secret string which is invalid - let invalid_client_secret_because_of_invalid_payment_id = - format!(r#""{invalid_global_payment_id}_secret_{secret}""#); - - // Create a client secret string which is invalid because of invalid secret - let invalid_client_secret_because_of_invalid_secret = - format!(r#""{invalid_global_payment_id}""#); - - let valid_client_secret = serde_json::from_str::<ClientSecret>(&valid_client_secret) - .expect("Failed to deserialize client_secret_str1"); - - let invalid_deser1 = serde_json::from_str::<ClientSecret>( - &invalid_client_secret_because_of_invalid_payment_id, - ); - - dbg!(&invalid_deser1); - - let invalid_deser2 = serde_json::from_str::<ClientSecret>( - &invalid_client_secret_because_of_invalid_secret, - ); - - dbg!(&invalid_deser2); - - assert_eq!(valid_client_secret.payment_id, valid_payment_global_id); - - assert_eq!(valid_client_secret.secret.peek(), &secret); - - assert_eq!( - invalid_deser1.err().unwrap().to_string(), - "Incorrect value provided for field: payment_id at line 1 column 70" - ); - - assert_eq!( - invalid_deser2.err().unwrap().to_string(), - "invalid value: string \"123_pay_1a961ed9093c48b09781bf8ab17ba6bd\", expected a string with '_secret_' at line 1 column 42" - ); - } - } -} - /// A type representing a range of time for filtering, including a mandatory start time and an optional end time. #[derive( Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema, diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 6753afc2d99..5034873e7ac 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -33,7 +33,6 @@ pub struct PaymentIntent { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, @@ -290,7 +289,6 @@ pub struct PaymentIntentNew { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 4c07445f710..9b16f56f350 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -921,8 +921,6 @@ diesel::table! { modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, setup_future_usage -> Nullable<FutureUsage>, - #[max_length = 128] - client_secret -> Varchar, #[max_length = 64] active_attempt_id -> Nullable<Varchar>, order_details -> Nullable<Array<Nullable<Jsonb>>>, diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index dedba889c68..7f757c64a72 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -403,8 +403,6 @@ pub struct PaymentIntent { #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: storage_enums::FutureUsage, - /// The client secret that is generated for the payment. This is used to authenticate the payment from client facing apis. - pub client_secret: common_utils::types::ClientSecret, /// The active attempt for the payment intent. This is the payment attempt that is currently active for the payment intent. pub active_attempt_id: Option<id_type::GlobalAttemptId>, /// The order details for the payment. @@ -526,22 +524,6 @@ impl PaymentIntent { .unwrap_or(Ok(common_enums::RequestIncrementalAuthorization::default())) } - /// Check if the client secret is associated with the payment and if it has been expired - pub fn validate_client_secret( - &self, - client_secret: &common_utils::types::ClientSecret, - ) -> Result<(), errors::api_error_response::ApiErrorResponse> { - common_utils::fp_utils::when(self.client_secret != *client_secret, || { - Err(errors::api_error_response::ApiErrorResponse::ClientSecretInvalid) - })?; - - common_utils::fp_utils::when(self.session_expiry < common_utils::date_time::now(), || { - Err(errors::api_error_response::ApiErrorResponse::ClientSecretExpired) - })?; - - Ok(()) - } - pub async fn create_domain_model_from_request( payment_id: &id_type::GlobalPaymentId, merchant_account: &merchant_account::MerchantAccount, @@ -566,7 +548,6 @@ impl PaymentIntent { .unwrap_or(common_utils::consts::DEFAULT_SESSION_EXPIRY), ), )); - let client_secret = payment_id.generate_client_secret(); let order_details = request.order_details.map(|order_details| { order_details .into_iter() @@ -589,7 +570,6 @@ impl PaymentIntent { modified_at: common_utils::date_time::now(), last_synced: None, setup_future_usage: request.setup_future_usage.unwrap_or_default(), - client_secret, active_attempt_id: None, order_details, allowed_payment_method_types, @@ -704,7 +684,6 @@ pub struct HeaderPayload { pub locale: Option<String>, pub x_app_id: Option<String>, pub x_redirect_uri: Option<String>, - pub client_secret: Option<common_utils::types::ClientSecret>, } impl HeaderPayload { @@ -725,6 +704,7 @@ where pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub sessions_token: Vec<SessionToken>, + pub client_secret: Option<Secret<String>>, } // TODO: Check if this can be merged with existing payment data diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 13452649447..9b429f462e4 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1561,7 +1561,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at, last_synced, setup_future_usage, - client_secret, active_attempt_id, order_details, allowed_payment_method_types, @@ -1611,7 +1610,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at, last_synced, setup_future_usage: Some(setup_future_usage), - client_secret, active_attempt_id, order_details: order_details.map(|order_details| { order_details @@ -1760,7 +1758,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, setup_future_usage: storage_model.setup_future_usage.unwrap_or_default(), - client_secret: storage_model.client_secret, active_attempt_id: storage_model.active_attempt_id, order_details: storage_model.order_details.map(|order_details| { order_details @@ -1836,7 +1833,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at: self.modified_at, last_synced: self.last_synced, setup_future_usage: Some(self.setup_future_usage), - client_secret: self.client_secret, active_attempt_id: self.active_attempt_id, order_details: self.order_details, allowed_payment_method_types: self diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index cd68709afa4..e13bf290bec 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2041,9 +2041,6 @@ pub(crate) async fn payments_create_and_confirm_intent( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response from payments core")?; - // Adding client secret to ensure client secret validation passes during confirm intent step - header_payload.client_secret = Some(create_intent_response.client_secret.clone()); - let payload = payments_api::PaymentsConfirmIntentRequest::from(&request); let confirm_intent_response = decide_authorize_or_setup_intent_flow( @@ -8013,6 +8010,8 @@ impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> { pub trait OperationSessionGetters<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt; fn get_payment_intent(&self) -> &storage::PaymentIntent; + #[cfg(feature = "v2")] + fn get_client_secret(&self) -> &Option<Secret<String>>; fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>; fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>; fn get_address(&self) -> &PaymentAddress; @@ -8054,6 +8053,8 @@ pub trait OperationSessionGetters<F> { pub trait OperationSessionSetters<F> { // Setter functions for PaymentData fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent); + #[cfg(feature = "v2")] + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>); fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt); fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>); fn set_email_if_not_present(&mut self, email: pii::Email); @@ -8361,6 +8362,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> { todo!() } + fn get_client_secret(&self) -> &Option<Secret<String>> { + &self.client_secret + } + fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } @@ -8493,7 +8498,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + self.client_secret = client_secret; + } fn set_payment_attempt(&mut self, _payment_attempt: storage::PaymentAttempt) { todo!() } @@ -8577,6 +8584,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent @@ -8709,7 +8719,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + todo!() + } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } @@ -8795,7 +8807,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { todo!() } - + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } @@ -8926,7 +8940,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + todo!() + } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = Some(payment_attempt); } @@ -9012,7 +9028,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } - + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } @@ -9145,7 +9163,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + todo!() + } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a701d16fe17..a4a3f7c7572 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3587,30 +3587,6 @@ pub fn authenticate_client_secret( } } -#[cfg(feature = "v2")] -// A function to manually authenticate the client secret with intent fulfillment time -pub fn authenticate_client_secret( - request_client_secret: Option<&common_utils::types::ClientSecret>, - payment_intent: &PaymentIntent, -) -> Result<(), errors::ApiErrorResponse> { - match (request_client_secret, &payment_intent.client_secret) { - (Some(req_cs), pi_cs) => { - if req_cs != pi_cs { - Err(errors::ApiErrorResponse::ClientSecretInvalid) - } else { - let current_timestamp = common_utils::date_time::now(); - - let session_expiry = payment_intent.session_expiry; - - fp_utils::when(current_timestamp > session_expiry, || { - Err(errors::ApiErrorResponse::ClientSecretExpired) - }) - } - } - _ => Ok(()), - } -} - pub(crate) fn validate_payment_status_against_allowed_statuses( intent_status: storage_enums::IntentStatus, allowed_statuses: &[storage_enums::IntentStatus], diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs index 11e5093cf00..a997aab457d 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -169,11 +169,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir // TODO (#7195): Add platform merchant account validation once publishable key auth is solved self.validate_status_for_operation(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header")?; - payment_intent.validate_client_secret(client_secret)?; let cell_id = state.conf.cell_information.id.clone(); diff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rs index 755c4e153ce..92572602adb 100644 --- a/crates/router/src/core/payments/operations/payment_create_intent.rs +++ b/crates/router/src/core/payments/operations/payment_create_intent.rs @@ -5,7 +5,7 @@ use async_trait::async_trait; use common_utils::{ errors::CustomResult, ext_traits::{AsyncExt, Encode, ValueExt}, - types::keymanager::ToEncryptable, + types::{authentication, keymanager::ToEncryptable}, }; use error_stack::ResultExt; use masking::PeekInterface; @@ -158,9 +158,19 @@ impl<F: Send + Clone + Sync> }) .attach_printable("failed while inserting new payment intent")?; + let client_secret = helpers::create_client_secret( + state, + merchant_account.get_id(), + authentication::ResourceId::Payment(payment_id.clone()), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to create client secret")?; + let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + client_secret: Some(client_secret.secret), sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/operations/payment_get_intent.rs b/crates/router/src/core/payments/operations/payment_get_intent.rs index 05f939ee31b..2e00b19c757 100644 --- a/crates/router/src/core/payments/operations/payment_get_intent.rs +++ b/crates/router/src/core/payments/operations/payment_get_intent.rs @@ -106,6 +106,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + // todo : add a way to fetch client secret if required + client_secret: None, sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs index 4e62899546b..d90dba639b1 100644 --- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs +++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs @@ -74,7 +74,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once publishable key auth is solved - helpers::authenticate_client_secret(Some(request.client_secret.peek()), &payment_intent)?; let mut payment_attempt = db diff --git a/crates/router/src/core/payments/operations/payment_session_intent.rs b/crates/router/src/core/payments/operations/payment_session_intent.rs index 79348e6e235..8b8bbae292e 100644 --- a/crates/router/src/core/payments/operations/payment_session_intent.rs +++ b/crates/router/src/core/payments/operations/payment_session_intent.rs @@ -138,15 +138,10 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme self.validate_status_for_operation(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header")?; - payment_intent.validate_client_secret(client_secret)?; - let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + client_secret: None, sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 455f2884324..49de2c77ec8 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -83,6 +83,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq payment_intent.client_secret.as_ref(), &payment_intent, )?; + payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 9d09d56515c..f74a433037d 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -112,7 +112,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> ], "update", )?; - helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; payment_intent.order_details = request diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs index 9b89ead615f..a1af12e9fc6 100644 --- a/crates/router/src/core/payments/operations/payment_update_intent.rs +++ b/crates/router/src/core/payments/operations/payment_update_intent.rs @@ -291,6 +291,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpda let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + client_secret: None, sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rs index df100d2e9b6..94c4341dee7 100644 --- a/crates/router/src/core/payments/payment_methods.rs +++ b/crates/router/src/core/payments/payment_methods.rs @@ -36,16 +36,6 @@ pub async fn list_payment_methods( validate_payment_status_for_payment_method_list(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header") - .change_context(errors::ApiErrorResponse::MissingRequiredField { - field_name: "client_secret header", - })?; - - payment_intent.validate_client_secret(client_secret)?; - let payment_connector_accounts = db .list_enabled_connector_accounts_by_profile_id( key_manager_state, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index eb5b3d88173..652811e5a8f 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1523,6 +1523,7 @@ where _merchant_account: &domain::MerchantAccount, ) -> RouterResponse<Self> { let payment_intent = payment_data.get_payment_intent(); + let client_secret = payment_data.get_client_secret(); Ok(services::ApplicationResponse::JsonWithHeaders(( Self { id: payment_intent.id.clone(), @@ -1531,7 +1532,7 @@ where amount_details: api_models::payments::AmountDetailsResponse::foreign_from( payment_intent.amount_details.clone(), ), - client_secret: payment_intent.client_secret.clone(), + client_secret: client_secret.clone(), merchant_reference_id: payment_intent.merchant_reference_id.clone(), routing_algorithm_id: payment_intent.routing_algorithm_id.clone(), capture_method: payment_intent.capture_method, @@ -1662,7 +1663,6 @@ where amount, customer_id: payment_intent.customer_id.clone(), connector: Some(connector), - client_secret: payment_intent.client_secret.clone(), created: payment_intent.created_at, payment_method_data, payment_method_type: Some(payment_attempt.payment_method_type), @@ -1760,7 +1760,6 @@ where .cloned() .map(From::from), shipping: self.payment_address.get_shipping().cloned().map(From::from), - client_secret: payment_intent.client_secret.clone(), created: payment_intent.created_at, payment_method_data, payment_method_type: self diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 7e3d6802b88..fb694d3f23c 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -2101,23 +2101,38 @@ where get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; - match db_client_secret.resource_id { - common_utils::types::authentication::ResourceId::Payment(global_payment_id) => { - return Err(errors::ApiErrorResponse::Unauthorized.into()) + match (&self.0, &db_client_secret.resource_id) { + ( + common_utils::types::authentication::ResourceId::Payment(self_id), + common_utils::types::authentication::ResourceId::Payment(db_id), + ) => { + fp_utils::when(self_id != db_id, || { + Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) + }); } - common_utils::types::authentication::ResourceId::Customer(global_customer_id) => { - if global_customer_id.get_string_repr() != self.0.to_str() { - return Err(errors::ApiErrorResponse::Unauthorized.into()); - } + + ( + common_utils::types::authentication::ResourceId::Customer(self_id), + common_utils::types::authentication::ResourceId::Customer(db_id), + ) => { + fp_utils::when(self_id != db_id, || { + Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) + }); } - common_utils::types::authentication::ResourceId::PaymentMethodSession( - global_payment_method_session_id, + + ( + common_utils::types::authentication::ResourceId::PaymentMethodSession(self_id), + common_utils::types::authentication::ResourceId::PaymentMethodSession(db_id), ) => { - if global_payment_method_session_id.get_string_repr() != self.0.to_str() { - return Err(errors::ApiErrorResponse::Unauthorized.into()); - } + fp_utils::when(self_id != db_id, || { + Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) + }); } - }; + + _ => { + return Err(errors::ApiErrorResponse::Unauthorized.into()); + } + } let (merchant_account, key_store) = state .store() diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index c11751c8324..4a8be05711f 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1652,14 +1652,6 @@ impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderP let x_redirect_uri = get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string()); - // TODO: combine publishable key and client secret when we unify the auth - let client_secret = get_header_value_by_key(X_CLIENT_SECRET.into(), headers)? - .map(common_utils::types::ClientSecret::from_str) - .transpose() - .change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "Invalid data received in client_secret header".into(), - })?; - Ok(Self { payment_confirm_source, // client_source, @@ -1671,7 +1663,6 @@ impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderP locale, x_app_id, x_redirect_uri, - client_secret, }) } } diff --git a/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql new file mode 100644 index 00000000000..215c3bf4125 --- /dev/null +++ b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent +ADD COLUMN client_secret VARCHAR(128); \ No newline at end of file diff --git a/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql new file mode 100644 index 00000000000..7463ea0cbc7 --- /dev/null +++ b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_intent DROP COLUMN client_secret; \ No newline at end of file
2025-03-26T14:11:03Z
Your PR Description## Type of Change - [x] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description 1. This commit changes how the client secret is generated 2. Change how client secret is made in Create Payment Intent Old `{Payment_id}_secret_{Secret}` `eg : pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo` New `cs_{Secret}` `eg: cs_0195d2be95ba7ef1a05066e163295562` 3. Client secret validation in the root level #7487 ``` &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( global_payment_id, )), ``` 3. And removes client secret from PaymentIntent, PaymentIntentNew, HeaderResponse 4. update authentication logic for global_payment_id in V2ClientAuth ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context ## How did you test it? For `/v2/payments/create-intent` Request ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_REbCm9NzneE8vUBmgWWZ' \ --header 'Authorization: ••••••' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"manual", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" } }' ``` Response ``` { "id": "12345_pay_0195d5b7ff767ac094321057ddd9f2eb", "status": "requires_payment_method", "amount_details": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "cs_0195d5b7ffaf700397ea3e418d0835f6", "profile_id": "pro_EhW92OOmycGn3j0clrbm", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "manual", "authentication_type": "no_three_ds", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "shipping": { "address": { "city": "Karwar", "country": null, "line1": null, "line2": null, "line3": null, "zip": "581301", "state": "Karnataka", "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "customer_id": null, "customer_present": "present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2025-03-27T04:04:20.409Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` For `/v2/payments/:id/payment-methods` Request ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195d65b6a2c7931ad28b04dba1be6c9/payment-methods' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_XTzqP0yNw5ndliWtB9MJ' \ --header 'Authorization: publishable-key=pk_dev_266ddc923fa940c8a97240b9e690756e,client-secret=cs_0195d65b6a7b7072acf186a4529ae9ad ' ``` Response ``` { "payment_methods_enabled": [ { "payment_method_type": "card_redirect", "payment_method_subtype": "card_redirect", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "card", "payment_method_subtype": "credit", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "card", "payment_method_subtype": "debit", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "google_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "apple_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "we_chat_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "ali_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "paypal", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "mb_way", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "klarna", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "affirm", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "afterpay_clearpay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "walley", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "giropay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "ideal", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "eps", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "bancontact_card", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "przelewy24", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "sofort", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "blik", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "trustly", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "online_banking_finland", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "online_banking_poland", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "ach", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "sepa", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "bacs", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "ach", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "sepa", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "bacs", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "becs", "required_fields": null, "surcharge_details": null } ], "customer_payment_methods": null } ``` For `/v2/payments/:id/confirm-intent` Request ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195d65b6a2c7931ad28b04dba1be6c9/confirm-intent' \ --header 'x-profile-id: pro_XTzqP0yNw5ndliWtB9MJ' \ --header 'Authorization: publishable-key=pk_dev_266ddc923fa940c8a97240b9e690756e,client-secret=cs_0195d65b6a7b7072acf186a4529ae9ad ' \ --header 'Content-Type: application/json' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "26", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit" } ``` Response ``` { "id": "12345_pay_0195d65b6a2c7931ad28b04dba1be6c9", "status": "failed", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "customer_id": null, "connector": "stripe", "client_secret": null, "created": "2025-03-27T06:47:50.083Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": null, "connector_reference_id": null, "merchant_connector_id": "mca_qB5no08zJFDBYPZBZdFR", "browser_info": null, "error": { "code": "No error code", "message": "No error message", "unified_code": null, "unified_message": null }, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds" } ``` ## 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.113.0
f532b70af9c8acddfd00752d7a3893ac68e3c1eb
f532b70af9c8acddfd00752d7a3893ac68e3c1eb
juspay/hyperswitch
juspay__hyperswitch-7650
Bug: refactor(payments): update authentication logic for global_payment_id in V2ClientAuth https://github.com/juspay/hyperswitch-cloud/issues/8862 ## Verify Confirm a Payment ### Using `x-client-secret` as `client_secret` ```curl curl --location 'https://integ.hyperswitch.io/api/v2/payments/12345_pay_0195acbb210178a0bfa801e9ad6ae338/confirm-intent' \ --header '<<Authorization Header>>' \ --header 'x-profile-id: pro_hIm1Djam2eJdIogn0la6' \ --header 'Content-Type: application/json' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit" }' ``` ```json { "error": { "type": "invalid_request", "message": "Missing required param: Authorization", "code": "IR_04" } } ``` ### Using `Authorization` as `client-secret={{client_secret}}` ```json { "error": { "type": "invalid_request", "message": "API key not provided or invalid API key used", "code": "IR_01" } } ``` ### Using `Authorization` as `publishable-key={{publishable_key}},client-secret={{client_secret}}` ```json { "error": { "type": "invalid_request", "message": "API key not provided or invalid API key used", "code": "IR_01" } } ``` ## Summary Confirming Payments needed `x-client-secret: client-secret` previously, so now it should work with `Authorization: publishable-key={{publishable_key}},client-secret={{client_secret}}`. But doesn't work with any of the above cases.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index de2cd1b0360..27936b2917c 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -17102,7 +17102,7 @@ "client_secret": { "type": "string", "description": "It's a token used for client side verification.", - "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo" + "example": "cs_0195b34da95d75239c6a4bf514458896" }, "profile_id": { "type": "string", @@ -17699,7 +17699,6 @@ "status", "amount", "customer_id", - "client_secret", "created" ], "properties": { @@ -17729,10 +17728,6 @@ "example": "stripe", "nullable": true }, - "client_secret": { - "type": "string", - "description": "It's a token used for client side verification." - }, "created": { "type": "string", "format": "date-time", diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 3cfadb0a57c..1a07a18f336 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -480,8 +480,8 @@ pub struct PaymentsIntentResponse { pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. - #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] - pub client_secret: common_utils::types::ClientSecret, + #[schema(value_type = String, example = "cs_0195b34da95d75239c6a4bf514458896")] + pub client_secret: Option<Secret<String>>, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] @@ -5576,10 +5576,6 @@ pub struct PaymentsResponse { #[schema(example = "stripe")] pub connector: Option<String>, - /// It's a token used for client side verification. - #[schema(value_type = String)] - pub client_secret: common_utils::types::ClientSecret, - /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] diff --git a/crates/common_utils/src/id_type/global_id/payment.rs b/crates/common_utils/src/id_type/global_id/payment.rs index 5de836cd486..22ac0d4c0a4 100644 --- a/crates/common_utils/src/id_type/global_id/payment.rs +++ b/crates/common_utils/src/id_type/global_id/payment.rs @@ -28,11 +28,6 @@ impl GlobalPaymentId { Self(global_id) } - /// Generate a new ClientId from self - pub fn generate_client_secret(&self) -> types::ClientSecret { - types::ClientSecret::new(self.clone(), generate_time_ordered_id_without_prefix()) - } - /// Generate the id for revenue recovery Execute PT workflow pub fn get_execute_revenue_recovery_id( &self, diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 11c9b17fae6..b9d245d48ce 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -686,261 +686,6 @@ where } } -#[cfg(feature = "v2")] -pub use client_secret_type::ClientSecret; -#[cfg(feature = "v2")] -mod client_secret_type { - use std::fmt; - - use masking::PeekInterface; - use router_env::logger; - - use super::*; - use crate::id_type; - - /// A domain type that can be used to represent a client secret - /// Client secret is generated for a payment and is used to authenticate the client side api calls - #[derive(Debug, PartialEq, Clone, AsExpression)] - #[diesel(sql_type = sql_types::Text)] - pub struct ClientSecret { - /// The payment id of the payment - pub payment_id: id_type::GlobalPaymentId, - /// The secret string - pub secret: masking::Secret<String>, - } - - impl ClientSecret { - pub(crate) fn get_string_repr(&self) -> String { - format!( - "{}_secret_{}", - self.payment_id.get_string_repr(), - self.secret.peek() - ) - } - - /// Create a new client secret - pub(crate) fn new(payment_id: id_type::GlobalPaymentId, secret: String) -> Self { - Self { - payment_id, - secret: masking::Secret::new(secret), - } - } - } - - impl FromStr for ClientSecret { - type Err = ParsingError; - - fn from_str(str_value: &str) -> Result<Self, Self::Err> { - let (payment_id, secret) = - str_value - .rsplit_once("_secret_") - .ok_or(ParsingError::EncodeError( - "Expected a string in the format '{payment_id}_secret_{secret}'", - ))?; - - let payment_id = id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned())) - .map_err(|err| { - logger::error!(global_payment_id_error=?err); - ParsingError::EncodeError("Error while constructing GlobalPaymentId") - })?; - - Ok(Self { - payment_id, - secret: masking::Secret::new(secret.to_owned()), - }) - } - } - - impl<'de> Deserialize<'de> for ClientSecret { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - struct ClientSecretVisitor; - - impl Visitor<'_> for ClientSecretVisitor { - type Value = ClientSecret; - - fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str("a string in the format '{payment_id}_secret_{secret}'") - } - - fn visit_str<E>(self, value: &str) -> Result<ClientSecret, E> - where - E: serde::de::Error, - { - let (payment_id, secret) = value.rsplit_once("_secret_").ok_or_else(|| { - E::invalid_value( - serde::de::Unexpected::Str(value), - &"a string with '_secret_'", - ) - })?; - - let payment_id = - id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned())) - .map_err(serde::de::Error::custom)?; - - Ok(ClientSecret { - payment_id, - secret: masking::Secret::new(secret.to_owned()), - }) - } - } - - deserializer.deserialize_str(ClientSecretVisitor) - } - } - - impl Serialize for ClientSecret { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: serde::ser::Serializer, - { - serializer.serialize_str(self.get_string_repr().as_str()) - } - } - - impl ToSql<sql_types::Text, diesel::pg::Pg> for ClientSecret - where - String: ToSql<sql_types::Text, diesel::pg::Pg>, - { - fn to_sql<'b>( - &'b self, - out: &mut Output<'b, '_, diesel::pg::Pg>, - ) -> diesel::serialize::Result { - let string_repr = self.get_string_repr(); - <String as ToSql<sql_types::Text, diesel::pg::Pg>>::to_sql( - &string_repr, - &mut out.reborrow(), - ) - } - } - - impl<DB> FromSql<sql_types::Text, DB> for ClientSecret - where - DB: Backend, - String: FromSql<sql_types::Text, DB>, - { - fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> { - let string_repr = String::from_sql(value)?; - let (payment_id, secret) = - string_repr - .rsplit_once("_secret_") - .ok_or(ParsingError::EncodeError( - "Expected a string in the format '{payment_id}_secret_{secret}'", - ))?; - - let payment_id = id_type::GlobalPaymentId::try_from(Cow::Owned(payment_id.to_owned())) - .map_err(|err| { - logger::error!(global_payment_id_error=?err); - ParsingError::EncodeError("Error while constructing GlobalPaymentId") - })?; - - Ok(Self { - payment_id, - secret: masking::Secret::new(secret.to_owned()), - }) - } - } - - impl<DB> Queryable<sql_types::Text, DB> for ClientSecret - where - DB: Backend, - Self: FromSql<sql_types::Text, DB>, - { - type Row = Self; - - fn build(row: Self::Row) -> deserialize::Result<Self> { - Ok(row) - } - } - crate::impl_serializable_secret_id_type!(ClientSecret); - #[cfg(test)] - mod client_secret_tests { - #![allow(clippy::expect_used)] - #![allow(clippy::unwrap_used)] - - use serde_json; - - use super::*; - use crate::id_type::GlobalPaymentId; - - #[test] - fn test_serialize_client_secret() { - let global_payment_id = "12345_pay_1a961ed9093c48b09781bf8ab17ba6bd"; - let secret = "fc34taHLw1ekPgNh92qr".to_string(); - - let expected_client_secret_string = format!("\"{global_payment_id}_secret_{secret}\""); - - let client_secret1 = ClientSecret { - payment_id: GlobalPaymentId::try_from(Cow::Borrowed(global_payment_id)).unwrap(), - secret: masking::Secret::new(secret), - }; - - let parsed_client_secret = - serde_json::to_string(&client_secret1).expect("Failed to serialize client_secret1"); - - assert_eq!(expected_client_secret_string, parsed_client_secret); - } - - #[test] - fn test_deserialize_client_secret() { - // This is a valid global id - let global_payment_id_str = "12345_pay_1a961ed9093c48b09781bf8ab17ba6bd"; - let secret = "fc34taHLw1ekPgNh92qr".to_string(); - - let valid_payment_global_id = - GlobalPaymentId::try_from(Cow::Borrowed(global_payment_id_str)) - .expect("Failed to create valid global payment id"); - - // This is an invalid global id because of the cell id being in invalid length - let invalid_global_payment_id = "123_pay_1a961ed9093c48b09781bf8ab17ba6bd"; - - // Create a client secret string which is valid - let valid_client_secret = format!(r#""{global_payment_id_str}_secret_{secret}""#); - - dbg!(&valid_client_secret); - - // Create a client secret string which is invalid - let invalid_client_secret_because_of_invalid_payment_id = - format!(r#""{invalid_global_payment_id}_secret_{secret}""#); - - // Create a client secret string which is invalid because of invalid secret - let invalid_client_secret_because_of_invalid_secret = - format!(r#""{invalid_global_payment_id}""#); - - let valid_client_secret = serde_json::from_str::<ClientSecret>(&valid_client_secret) - .expect("Failed to deserialize client_secret_str1"); - - let invalid_deser1 = serde_json::from_str::<ClientSecret>( - &invalid_client_secret_because_of_invalid_payment_id, - ); - - dbg!(&invalid_deser1); - - let invalid_deser2 = serde_json::from_str::<ClientSecret>( - &invalid_client_secret_because_of_invalid_secret, - ); - - dbg!(&invalid_deser2); - - assert_eq!(valid_client_secret.payment_id, valid_payment_global_id); - - assert_eq!(valid_client_secret.secret.peek(), &secret); - - assert_eq!( - invalid_deser1.err().unwrap().to_string(), - "Incorrect value provided for field: payment_id at line 1 column 70" - ); - - assert_eq!( - invalid_deser2.err().unwrap().to_string(), - "invalid value: string \"123_pay_1a961ed9093c48b09781bf8ab17ba6bd\", expected a string with '_secret_' at line 1 column 42" - ); - } - } -} - /// A type representing a range of time for filtering, including a mandatory start time and an optional end time. #[derive( Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema, diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 6753afc2d99..5034873e7ac 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -33,7 +33,6 @@ pub struct PaymentIntent { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, @@ -290,7 +289,6 @@ pub struct PaymentIntentNew { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 4c07445f710..9b16f56f350 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -921,8 +921,6 @@ diesel::table! { modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, setup_future_usage -> Nullable<FutureUsage>, - #[max_length = 128] - client_secret -> Varchar, #[max_length = 64] active_attempt_id -> Nullable<Varchar>, order_details -> Nullable<Array<Nullable<Jsonb>>>, diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index dedba889c68..7f757c64a72 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -403,8 +403,6 @@ pub struct PaymentIntent { #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: storage_enums::FutureUsage, - /// The client secret that is generated for the payment. This is used to authenticate the payment from client facing apis. - pub client_secret: common_utils::types::ClientSecret, /// The active attempt for the payment intent. This is the payment attempt that is currently active for the payment intent. pub active_attempt_id: Option<id_type::GlobalAttemptId>, /// The order details for the payment. @@ -526,22 +524,6 @@ impl PaymentIntent { .unwrap_or(Ok(common_enums::RequestIncrementalAuthorization::default())) } - /// Check if the client secret is associated with the payment and if it has been expired - pub fn validate_client_secret( - &self, - client_secret: &common_utils::types::ClientSecret, - ) -> Result<(), errors::api_error_response::ApiErrorResponse> { - common_utils::fp_utils::when(self.client_secret != *client_secret, || { - Err(errors::api_error_response::ApiErrorResponse::ClientSecretInvalid) - })?; - - common_utils::fp_utils::when(self.session_expiry < common_utils::date_time::now(), || { - Err(errors::api_error_response::ApiErrorResponse::ClientSecretExpired) - })?; - - Ok(()) - } - pub async fn create_domain_model_from_request( payment_id: &id_type::GlobalPaymentId, merchant_account: &merchant_account::MerchantAccount, @@ -566,7 +548,6 @@ impl PaymentIntent { .unwrap_or(common_utils::consts::DEFAULT_SESSION_EXPIRY), ), )); - let client_secret = payment_id.generate_client_secret(); let order_details = request.order_details.map(|order_details| { order_details .into_iter() @@ -589,7 +570,6 @@ impl PaymentIntent { modified_at: common_utils::date_time::now(), last_synced: None, setup_future_usage: request.setup_future_usage.unwrap_or_default(), - client_secret, active_attempt_id: None, order_details, allowed_payment_method_types, @@ -704,7 +684,6 @@ pub struct HeaderPayload { pub locale: Option<String>, pub x_app_id: Option<String>, pub x_redirect_uri: Option<String>, - pub client_secret: Option<common_utils::types::ClientSecret>, } impl HeaderPayload { @@ -725,6 +704,7 @@ where pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub sessions_token: Vec<SessionToken>, + pub client_secret: Option<Secret<String>>, } // TODO: Check if this can be merged with existing payment data diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 13452649447..9b429f462e4 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1561,7 +1561,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at, last_synced, setup_future_usage, - client_secret, active_attempt_id, order_details, allowed_payment_method_types, @@ -1611,7 +1610,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at, last_synced, setup_future_usage: Some(setup_future_usage), - client_secret, active_attempt_id, order_details: order_details.map(|order_details| { order_details @@ -1760,7 +1758,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at: storage_model.modified_at, last_synced: storage_model.last_synced, setup_future_usage: storage_model.setup_future_usage.unwrap_or_default(), - client_secret: storage_model.client_secret, active_attempt_id: storage_model.active_attempt_id, order_details: storage_model.order_details.map(|order_details| { order_details @@ -1836,7 +1833,6 @@ impl behaviour::Conversion for PaymentIntent { modified_at: self.modified_at, last_synced: self.last_synced, setup_future_usage: Some(self.setup_future_usage), - client_secret: self.client_secret, active_attempt_id: self.active_attempt_id, order_details: self.order_details, allowed_payment_method_types: self diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index cd68709afa4..e13bf290bec 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2041,9 +2041,6 @@ pub(crate) async fn payments_create_and_confirm_intent( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response from payments core")?; - // Adding client secret to ensure client secret validation passes during confirm intent step - header_payload.client_secret = Some(create_intent_response.client_secret.clone()); - let payload = payments_api::PaymentsConfirmIntentRequest::from(&request); let confirm_intent_response = decide_authorize_or_setup_intent_flow( @@ -8013,6 +8010,8 @@ impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> { pub trait OperationSessionGetters<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt; fn get_payment_intent(&self) -> &storage::PaymentIntent; + #[cfg(feature = "v2")] + fn get_client_secret(&self) -> &Option<Secret<String>>; fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>; fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>; fn get_address(&self) -> &PaymentAddress; @@ -8054,6 +8053,8 @@ pub trait OperationSessionGetters<F> { pub trait OperationSessionSetters<F> { // Setter functions for PaymentData fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent); + #[cfg(feature = "v2")] + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>); fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt); fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>); fn set_email_if_not_present(&mut self, email: pii::Email); @@ -8361,6 +8362,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> { todo!() } + fn get_client_secret(&self) -> &Option<Secret<String>> { + &self.client_secret + } + fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } @@ -8493,7 +8498,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + self.client_secret = client_secret; + } fn set_payment_attempt(&mut self, _payment_attempt: storage::PaymentAttempt) { todo!() } @@ -8577,6 +8584,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent @@ -8709,7 +8719,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + todo!() + } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } @@ -8795,7 +8807,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { todo!() } - + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } @@ -8926,7 +8940,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + todo!() + } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = Some(payment_attempt); } @@ -9012,7 +9028,9 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } - + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } @@ -9145,7 +9163,9 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } - + fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) { + todo!() + } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a701d16fe17..a4a3f7c7572 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3587,30 +3587,6 @@ pub fn authenticate_client_secret( } } -#[cfg(feature = "v2")] -// A function to manually authenticate the client secret with intent fulfillment time -pub fn authenticate_client_secret( - request_client_secret: Option<&common_utils::types::ClientSecret>, - payment_intent: &PaymentIntent, -) -> Result<(), errors::ApiErrorResponse> { - match (request_client_secret, &payment_intent.client_secret) { - (Some(req_cs), pi_cs) => { - if req_cs != pi_cs { - Err(errors::ApiErrorResponse::ClientSecretInvalid) - } else { - let current_timestamp = common_utils::date_time::now(); - - let session_expiry = payment_intent.session_expiry; - - fp_utils::when(current_timestamp > session_expiry, || { - Err(errors::ApiErrorResponse::ClientSecretExpired) - }) - } - } - _ => Ok(()), - } -} - pub(crate) fn validate_payment_status_against_allowed_statuses( intent_status: storage_enums::IntentStatus, allowed_statuses: &[storage_enums::IntentStatus], diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs index 11e5093cf00..a997aab457d 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -169,11 +169,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir // TODO (#7195): Add platform merchant account validation once publishable key auth is solved self.validate_status_for_operation(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header")?; - payment_intent.validate_client_secret(client_secret)?; let cell_id = state.conf.cell_information.id.clone(); diff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rs index 755c4e153ce..92572602adb 100644 --- a/crates/router/src/core/payments/operations/payment_create_intent.rs +++ b/crates/router/src/core/payments/operations/payment_create_intent.rs @@ -5,7 +5,7 @@ use async_trait::async_trait; use common_utils::{ errors::CustomResult, ext_traits::{AsyncExt, Encode, ValueExt}, - types::keymanager::ToEncryptable, + types::{authentication, keymanager::ToEncryptable}, }; use error_stack::ResultExt; use masking::PeekInterface; @@ -158,9 +158,19 @@ impl<F: Send + Clone + Sync> }) .attach_printable("failed while inserting new payment intent")?; + let client_secret = helpers::create_client_secret( + state, + merchant_account.get_id(), + authentication::ResourceId::Payment(payment_id.clone()), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to create client secret")?; + let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + client_secret: Some(client_secret.secret), sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/operations/payment_get_intent.rs b/crates/router/src/core/payments/operations/payment_get_intent.rs index 05f939ee31b..2e00b19c757 100644 --- a/crates/router/src/core/payments/operations/payment_get_intent.rs +++ b/crates/router/src/core/payments/operations/payment_get_intent.rs @@ -106,6 +106,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + // todo : add a way to fetch client secret if required + client_secret: None, sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs index 4e62899546b..d90dba639b1 100644 --- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs +++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs @@ -74,7 +74,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once publishable key auth is solved - helpers::authenticate_client_secret(Some(request.client_secret.peek()), &payment_intent)?; let mut payment_attempt = db diff --git a/crates/router/src/core/payments/operations/payment_session_intent.rs b/crates/router/src/core/payments/operations/payment_session_intent.rs index 79348e6e235..8b8bbae292e 100644 --- a/crates/router/src/core/payments/operations/payment_session_intent.rs +++ b/crates/router/src/core/payments/operations/payment_session_intent.rs @@ -138,15 +138,10 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme self.validate_status_for_operation(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header")?; - payment_intent.validate_client_secret(client_secret)?; - let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + client_secret: None, sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 455f2884324..49de2c77ec8 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -83,6 +83,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq payment_intent.client_secret.as_ref(), &payment_intent, )?; + payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 9d09d56515c..f74a433037d 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -112,7 +112,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> ], "update", )?; - helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; payment_intent.order_details = request diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs index 9b89ead615f..a1af12e9fc6 100644 --- a/crates/router/src/core/payments/operations/payment_update_intent.rs +++ b/crates/router/src/core/payments/operations/payment_update_intent.rs @@ -291,6 +291,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpda let payment_data = payments::PaymentIntentData { flow: PhantomData, payment_intent, + client_secret: None, sessions_token: vec![], }; diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rs index df100d2e9b6..94c4341dee7 100644 --- a/crates/router/src/core/payments/payment_methods.rs +++ b/crates/router/src/core/payments/payment_methods.rs @@ -36,16 +36,6 @@ pub async fn list_payment_methods( validate_payment_status_for_payment_method_list(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header") - .change_context(errors::ApiErrorResponse::MissingRequiredField { - field_name: "client_secret header", - })?; - - payment_intent.validate_client_secret(client_secret)?; - let payment_connector_accounts = db .list_enabled_connector_accounts_by_profile_id( key_manager_state, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index eb5b3d88173..652811e5a8f 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1523,6 +1523,7 @@ where _merchant_account: &domain::MerchantAccount, ) -> RouterResponse<Self> { let payment_intent = payment_data.get_payment_intent(); + let client_secret = payment_data.get_client_secret(); Ok(services::ApplicationResponse::JsonWithHeaders(( Self { id: payment_intent.id.clone(), @@ -1531,7 +1532,7 @@ where amount_details: api_models::payments::AmountDetailsResponse::foreign_from( payment_intent.amount_details.clone(), ), - client_secret: payment_intent.client_secret.clone(), + client_secret: client_secret.clone(), merchant_reference_id: payment_intent.merchant_reference_id.clone(), routing_algorithm_id: payment_intent.routing_algorithm_id.clone(), capture_method: payment_intent.capture_method, @@ -1662,7 +1663,6 @@ where amount, customer_id: payment_intent.customer_id.clone(), connector: Some(connector), - client_secret: payment_intent.client_secret.clone(), created: payment_intent.created_at, payment_method_data, payment_method_type: Some(payment_attempt.payment_method_type), @@ -1760,7 +1760,6 @@ where .cloned() .map(From::from), shipping: self.payment_address.get_shipping().cloned().map(From::from), - client_secret: payment_intent.client_secret.clone(), created: payment_intent.created_at, payment_method_data, payment_method_type: self diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 7e3d6802b88..fb694d3f23c 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -2101,23 +2101,38 @@ where get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; - match db_client_secret.resource_id { - common_utils::types::authentication::ResourceId::Payment(global_payment_id) => { - return Err(errors::ApiErrorResponse::Unauthorized.into()) + match (&self.0, &db_client_secret.resource_id) { + ( + common_utils::types::authentication::ResourceId::Payment(self_id), + common_utils::types::authentication::ResourceId::Payment(db_id), + ) => { + fp_utils::when(self_id != db_id, || { + Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) + }); } - common_utils::types::authentication::ResourceId::Customer(global_customer_id) => { - if global_customer_id.get_string_repr() != self.0.to_str() { - return Err(errors::ApiErrorResponse::Unauthorized.into()); - } + + ( + common_utils::types::authentication::ResourceId::Customer(self_id), + common_utils::types::authentication::ResourceId::Customer(db_id), + ) => { + fp_utils::when(self_id != db_id, || { + Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) + }); } - common_utils::types::authentication::ResourceId::PaymentMethodSession( - global_payment_method_session_id, + + ( + common_utils::types::authentication::ResourceId::PaymentMethodSession(self_id), + common_utils::types::authentication::ResourceId::PaymentMethodSession(db_id), ) => { - if global_payment_method_session_id.get_string_repr() != self.0.to_str() { - return Err(errors::ApiErrorResponse::Unauthorized.into()); - } + fp_utils::when(self_id != db_id, || { + Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized) + }); } - }; + + _ => { + return Err(errors::ApiErrorResponse::Unauthorized.into()); + } + } let (merchant_account, key_store) = state .store() diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index c11751c8324..4a8be05711f 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1652,14 +1652,6 @@ impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderP let x_redirect_uri = get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string()); - // TODO: combine publishable key and client secret when we unify the auth - let client_secret = get_header_value_by_key(X_CLIENT_SECRET.into(), headers)? - .map(common_utils::types::ClientSecret::from_str) - .transpose() - .change_context(errors::ApiErrorResponse::InvalidRequestData { - message: "Invalid data received in client_secret header".into(), - })?; - Ok(Self { payment_confirm_source, // client_source, @@ -1671,7 +1663,6 @@ impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderP locale, x_app_id, x_redirect_uri, - client_secret, }) } } diff --git a/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql new file mode 100644 index 00000000000..215c3bf4125 --- /dev/null +++ b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent +ADD COLUMN client_secret VARCHAR(128); \ No newline at end of file diff --git a/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql new file mode 100644 index 00000000000..7463ea0cbc7 --- /dev/null +++ b/v2_migrations/2025-03-25-090538_remove_client_secret_from_payment_intents/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_intent DROP COLUMN client_secret; \ No newline at end of file
2025-03-26T14:11:03Z
Your PR Description## Type of Change - [x] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description 1. This commit changes how the client secret is generated 2. Change how client secret is made in Create Payment Intent Old `{Payment_id}_secret_{Secret}` `eg : pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo` New `cs_{Secret}` `eg: cs_0195d2be95ba7ef1a05066e163295562` 3. Client secret validation in the root level #7487 ``` &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( global_payment_id, )), ``` 3. And removes client secret from PaymentIntent, PaymentIntentNew, HeaderResponse 4. update authentication logic for global_payment_id in V2ClientAuth ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context ## How did you test it? For `/v2/payments/create-intent` Request ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_REbCm9NzneE8vUBmgWWZ' \ --header 'Authorization: ••••••' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"manual", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" } }' ``` Response ``` { "id": "12345_pay_0195d5b7ff767ac094321057ddd9f2eb", "status": "requires_payment_method", "amount_details": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "cs_0195d5b7ffaf700397ea3e418d0835f6", "profile_id": "pro_EhW92OOmycGn3j0clrbm", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "manual", "authentication_type": "no_three_ds", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "shipping": { "address": { "city": "Karwar", "country": null, "line1": null, "line2": null, "line3": null, "zip": "581301", "state": "Karnataka", "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "customer_id": null, "customer_present": "present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2025-03-27T04:04:20.409Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` For `/v2/payments/:id/payment-methods` Request ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195d65b6a2c7931ad28b04dba1be6c9/payment-methods' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_XTzqP0yNw5ndliWtB9MJ' \ --header 'Authorization: publishable-key=pk_dev_266ddc923fa940c8a97240b9e690756e,client-secret=cs_0195d65b6a7b7072acf186a4529ae9ad ' ``` Response ``` { "payment_methods_enabled": [ { "payment_method_type": "card_redirect", "payment_method_subtype": "card_redirect", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "card", "payment_method_subtype": "credit", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "card", "payment_method_subtype": "debit", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "google_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "apple_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "we_chat_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "ali_pay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "paypal", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "mb_way", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "klarna", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "affirm", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "afterpay_clearpay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "walley", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "giropay", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "ideal", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "eps", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "bancontact_card", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "przelewy24", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "sofort", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "blik", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "trustly", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "online_banking_finland", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "online_banking_poland", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "ach", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "sepa", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "bacs", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "ach", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "sepa", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "bacs", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "becs", "required_fields": null, "surcharge_details": null } ], "customer_payment_methods": null } ``` For `/v2/payments/:id/confirm-intent` Request ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195d65b6a2c7931ad28b04dba1be6c9/confirm-intent' \ --header 'x-profile-id: pro_XTzqP0yNw5ndliWtB9MJ' \ --header 'Authorization: publishable-key=pk_dev_266ddc923fa940c8a97240b9e690756e,client-secret=cs_0195d65b6a7b7072acf186a4529ae9ad ' \ --header 'Content-Type: application/json' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "26", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit" } ``` Response ``` { "id": "12345_pay_0195d65b6a2c7931ad28b04dba1be6c9", "status": "failed", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "customer_id": null, "connector": "stripe", "client_secret": null, "created": "2025-03-27T06:47:50.083Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": null, "connector_reference_id": null, "merchant_connector_id": "mca_qB5no08zJFDBYPZBZdFR", "browser_info": null, "error": { "code": "No error code", "message": "No error message", "unified_code": null, "unified_message": null }, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds" } ``` ## 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.113.0
f532b70af9c8acddfd00752d7a3893ac68e3c1eb
f532b70af9c8acddfd00752d7a3893ac68e3c1eb
juspay/hyperswitch
juspay__hyperswitch-7661
Bug: feat(router): Support `card` in `payment_method_subtype` [V2] `payment_method_subtype` field needs to be made mandatory and `card` needs to be added as a supported enum variant. This is needed for parity with industry standard analytics hierarchy
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index de2cd1b0360..0b7da8463b9 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -15184,6 +15184,7 @@ "type": "object", "required": [ "payment_method_type", + "payment_method_subtype", "customer_id", "payment_method_data" ], @@ -15192,12 +15193,7 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "allOf": [ - { - "$ref": "#/components/schemas/PaymentMethodType" - } - ], - "nullable": true + "$ref": "#/components/schemas/PaymentMethodType" }, "metadata": { "type": "object", @@ -16664,7 +16660,8 @@ "description": "Request for Payment Intent Confirm", "required": [ "payment_method_data", - "payment_method_type" + "payment_method_type", + "payment_method_subtype" ], "properties": { "return_url": { @@ -16680,12 +16677,7 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "allOf": [ - { - "$ref": "#/components/schemas/PaymentMethodType" - } - ], - "nullable": true + "$ref": "#/components/schemas/PaymentMethodType" }, "shipping": { "allOf": [ @@ -17468,7 +17460,8 @@ "amount_details", "customer_id", "payment_method_data", - "payment_method_type" + "payment_method_type", + "payment_method_subtype" ], "properties": { "amount_details": { @@ -17660,12 +17653,7 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "allOf": [ - { - "$ref": "#/components/schemas/PaymentMethodType" - } - ], - "nullable": true + "$ref": "#/components/schemas/PaymentMethodType" }, "customer_acceptance": { "allOf": [ diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 3590537a083..4313d224019 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -116,8 +116,8 @@ pub struct PaymentMethodCreate { pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. - #[schema(value_type = Option<PaymentMethodType>,example = "credit")] - pub payment_method_subtype: Option<api_enums::PaymentMethodType>, + #[schema(value_type = PaymentMethodType,example = "google_pay")] + pub payment_method_subtype: api_enums::PaymentMethodType, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] @@ -2806,8 +2806,8 @@ pub struct PaymentMethodSessionConfirmRequest { pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype - #[schema(value_type = PaymentMethodType, example = "credit")] - pub payment_method_subtype: Option<common_enums::PaymentMethodType>, + #[schema(value_type = PaymentMethodType, example = "google_pay")] + pub payment_method_subtype: common_enums::PaymentMethodType, /// The payment instrument data to be used for the payment #[schema(value_type = PaymentMethodDataRequest)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 3cfadb0a57c..a2d3090683f 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5247,8 +5247,8 @@ pub struct PaymentsConfirmIntentRequest { pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided - #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] - pub payment_method_subtype: Option<api_enums::PaymentMethodType>, + #[schema(value_type = PaymentMethodType, example = "apple_pay")] + pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, @@ -5416,8 +5416,8 @@ pub struct PaymentsRequest { pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided - #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] - pub payment_method_subtype: Option<api_enums::PaymentMethodType>, + #[schema(value_type = PaymentMethodType, example = "apple_pay")] + pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] @@ -8506,7 +8506,7 @@ pub struct PaymentRevenueRecoveryMetadata { pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] - pub payment_method_subtype: Option<common_enums::PaymentMethodType>, + pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, @@ -8587,7 +8587,7 @@ pub struct PaymentsAttemptRecordRequest { /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] - pub payment_method_subtype: Option<api_enums::PaymentMethodType>, + pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, diff --git a/crates/common_enums/Cargo.toml b/crates/common_enums/Cargo.toml index 5db5393644a..6f2d96a5838 100644 --- a/crates/common_enums/Cargo.toml +++ b/crates/common_enums/Cargo.toml @@ -11,6 +11,7 @@ license.workspace = true dummy_connector = [] openapi = [] payouts = [] +v2 = [] [dependencies] diesel = { version = "2.2.3", features = ["postgres", "128-column-tables"] } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 1697b1386c4..ca3968ed64d 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1755,6 +1755,8 @@ pub enum PaymentMethodType { BcaBankTransfer, BniVa, BriVa, + #[cfg(feature = "v2")] + Card, CardRedirect, CimbVa, #[serde(rename = "classic")] @@ -1867,6 +1869,8 @@ impl PaymentMethodType { Self::CardRedirect => "Card Redirect", Self::CimbVa => "CIMB Virtual Account", Self::ClassicReward => "Classic Reward", + #[cfg(feature = "v2")] + Self::Card => "Card", Self::Credit => "Credit Card", Self::CryptoCurrency => "Crypto", Self::Cashapp => "Cash App", diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index 6ff3bad4add..2a130edbd84 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1815,6 +1815,8 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::CimbVa => Self::BankTransfer, PaymentMethodType::ClassicReward => Self::Reward, PaymentMethodType::Credit => Self::Card, + #[cfg(feature = "v2")] + PaymentMethodType::Card => Self::Card, PaymentMethodType::CryptoCurrency => Self::Crypto, PaymentMethodType::Dana => Self::Wallet, PaymentMethodType::DanamonVa => Self::BankTransfer, diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 33b51ebdf9c..a3599fc1b47 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -91,7 +91,7 @@ pub struct PaymentAttempt { pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, - pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, + pub payment_method_subtype: storage_enums::PaymentMethodType, pub routing_result: Option<serde_json::Value>, pub authentication_applied: Option<common_enums::AuthenticationType>, pub external_reference_id: Option<String>, @@ -322,7 +322,7 @@ pub struct PaymentAttemptNew { pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, - pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, + pub payment_method_subtype: storage_enums::PaymentMethodType, pub id: id_type::GlobalAttemptId, pub connector_token_details: Option<ConnectorTokenDetails>, pub card_discovery: Option<storage_enums::CardDiscovery>, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 4c07445f710..b89daa09698 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -878,7 +878,7 @@ diesel::table! { #[max_length = 128] connector_payment_id -> Nullable<Varchar>, #[max_length = 64] - payment_method_subtype -> Nullable<Varchar>, + payment_method_subtype -> Varchar, routing_result -> Nullable<Jsonb>, authentication_applied -> Nullable<AuthenticationType>, #[max_length = 128] diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index dc69c0a323a..2314d2bf4ca 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -63,7 +63,7 @@ impl FeatureMetadata { pub fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> { self.payment_revenue_recovery_metadata .as_ref() - .and_then(|val| val.payment_method_subtype) + .map(|rrm| rrm.payment_method_subtype) } pub fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod> { @@ -168,7 +168,7 @@ pub struct PaymentRevenueRecoveryMetadata { ///Payment Method Type pub payment_method_type: common_enums::enums::PaymentMethod, /// PaymentMethod Subtype - pub payment_method_subtype: Option<common_enums::enums::PaymentMethodType>, + pub payment_method_subtype: common_enums::enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. pub connector: common_enums::connector_enums::Connector, } diff --git a/crates/euclid/Cargo.toml b/crates/euclid/Cargo.toml index 8f1320db234..a607531d87f 100644 --- a/crates/euclid/Cargo.toml +++ b/crates/euclid/Cargo.toml @@ -28,6 +28,7 @@ ast_parser = ["dep:nom"] valued_jit = [] dummy_connector = [] payouts = [] +v2 = ["common_enums/v2"] [dev-dependencies] criterion = "0.5" diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index ef7449e1c1b..2cf8301417c 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -27,6 +27,8 @@ pub use crate::enums::{PayoutBankTransferType, PayoutType, PayoutWalletType}; pub enum CardType { Credit, Debit, + #[cfg(feature = "v2")] + Card, } #[derive( diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index e58a6e28bdb..ace617fb365 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -16,6 +16,8 @@ impl From<enums::CardType> for global_enums::PaymentMethodType { match value { enums::CardType::Credit => Self::Credit, enums::CardType::Debit => Self::Debit, + #[cfg(feature = "v2")] + enums::CardType::Card => Self::Card, } } } diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index d85c23e2489..b4b512b5234 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -8,6 +8,8 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet match self.0 { global_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)), global_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)), + #[cfg(feature = "v2")] + global_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)), global_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), global_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), global_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), diff --git a/crates/hyperswitch_connectors/src/connectors/adyen.rs b/crates/hyperswitch_connectors/src/connectors/adyen.rs index 7550fc2677f..a9b23522516 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen.rs @@ -163,6 +163,7 @@ impl ConnectorValidation for Adyen { let connector = self.id(); match pmt { Some(payment_method_type) => match payment_method_type { + #[cfg(feature = "v1")] PaymentMethodType::Affirm | PaymentMethodType::AfterpayClearpay | PaymentMethodType::ApplePay @@ -187,6 +188,32 @@ impl ConnectorValidation for Adyen { ) } }, + #[cfg(feature = "v2")] + PaymentMethodType::Affirm + | PaymentMethodType::AfterpayClearpay + | PaymentMethodType::ApplePay + | PaymentMethodType::Credit + | PaymentMethodType::Debit + | PaymentMethodType::Card + | PaymentMethodType::GooglePay + | PaymentMethodType::MobilePay + | PaymentMethodType::PayBright + | PaymentMethodType::Sepa + | PaymentMethodType::Vipps + | PaymentMethodType::Venmo + | PaymentMethodType::Paypal => match capture_method { + enums::CaptureMethod::Automatic + | enums::CaptureMethod::SequentialAutomatic + | enums::CaptureMethod::Manual + | enums::CaptureMethod::ManualMultiple => Ok(()), + enums::CaptureMethod::Scheduled => { + capture_method_not_supported!( + connector, + capture_method, + payment_method_type + ) + } + }, PaymentMethodType::Ach | PaymentMethodType::SamsungPay | PaymentMethodType::Paze diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index ba523fd6235..101a9b753ad 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -447,9 +447,8 @@ impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptD let payment_method_details: ChargebeePaymentMethodDetails = serde_json::from_str(&item.content.transaction.payment_method_details) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - let payment_method_sub_type = Some(enums::PaymentMethodType::from( - payment_method_details.card.funding_type, - )); + let payment_method_sub_type = + enums::PaymentMethodType::from(payment_method_details.card.funding_type); Ok(Self { amount, currency, diff --git a/crates/hyperswitch_connectors/src/connectors/klarna.rs b/crates/hyperswitch_connectors/src/connectors/klarna.rs index bba7dd7e6ac..d2be42a1828 100644 --- a/crates/hyperswitch_connectors/src/connectors/klarna.rs +++ b/crates/hyperswitch_connectors/src/connectors/klarna.rs @@ -544,6 +544,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData ) => Ok(format!( "{endpoint}payments/v1/authorizations/{token}/order", )), + #[cfg(feature = "v1")] ( common_enums::PaymentExperience::DisplayQrCode | common_enums::PaymentExperience::DisplayWaitScreen @@ -656,6 +657,120 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData message: payment_method_type.to_string(), connector: "klarna", })), + #[cfg(feature = "v2")] + ( + common_enums::PaymentExperience::DisplayQrCode + | common_enums::PaymentExperience::DisplayWaitScreen + | common_enums::PaymentExperience::InvokePaymentApp + | common_enums::PaymentExperience::InvokeSdkClient + | common_enums::PaymentExperience::LinkWallet + | common_enums::PaymentExperience::OneClick + | common_enums::PaymentExperience::RedirectToUrl + | common_enums::PaymentExperience::CollectOtp, + common_enums::PaymentMethodType::Ach + | common_enums::PaymentMethodType::Affirm + | common_enums::PaymentMethodType::AfterpayClearpay + | common_enums::PaymentMethodType::Alfamart + | common_enums::PaymentMethodType::AliPay + | common_enums::PaymentMethodType::AliPayHk + | common_enums::PaymentMethodType::Alma + | common_enums::PaymentMethodType::AmazonPay + | common_enums::PaymentMethodType::ApplePay + | common_enums::PaymentMethodType::Atome + | common_enums::PaymentMethodType::Bacs + | common_enums::PaymentMethodType::BancontactCard + | common_enums::PaymentMethodType::Becs + | common_enums::PaymentMethodType::Benefit + | common_enums::PaymentMethodType::Bizum + | common_enums::PaymentMethodType::Blik + | common_enums::PaymentMethodType::Boleto + | common_enums::PaymentMethodType::BcaBankTransfer + | common_enums::PaymentMethodType::BniVa + | common_enums::PaymentMethodType::BriVa + | common_enums::PaymentMethodType::CardRedirect + | common_enums::PaymentMethodType::CimbVa + | common_enums::PaymentMethodType::ClassicReward + | common_enums::PaymentMethodType::Credit + | common_enums::PaymentMethodType::Card + | common_enums::PaymentMethodType::CryptoCurrency + | common_enums::PaymentMethodType::Cashapp + | common_enums::PaymentMethodType::Dana + | common_enums::PaymentMethodType::DanamonVa + | common_enums::PaymentMethodType::Debit + | common_enums::PaymentMethodType::DirectCarrierBilling + | common_enums::PaymentMethodType::Efecty + | common_enums::PaymentMethodType::Eft + | common_enums::PaymentMethodType::Eps + | common_enums::PaymentMethodType::Evoucher + | common_enums::PaymentMethodType::Giropay + | common_enums::PaymentMethodType::Givex + | common_enums::PaymentMethodType::GooglePay + | common_enums::PaymentMethodType::GoPay + | common_enums::PaymentMethodType::Gcash + | common_enums::PaymentMethodType::Ideal + | common_enums::PaymentMethodType::Interac + | common_enums::PaymentMethodType::Indomaret + | common_enums::PaymentMethodType::Klarna + | common_enums::PaymentMethodType::KakaoPay + | common_enums::PaymentMethodType::MandiriVa + | common_enums::PaymentMethodType::Knet + | common_enums::PaymentMethodType::MbWay + | common_enums::PaymentMethodType::MobilePay + | common_enums::PaymentMethodType::Momo + | common_enums::PaymentMethodType::MomoAtm + | common_enums::PaymentMethodType::Multibanco + | common_enums::PaymentMethodType::LocalBankRedirect + | common_enums::PaymentMethodType::OnlineBankingThailand + | common_enums::PaymentMethodType::OnlineBankingCzechRepublic + | common_enums::PaymentMethodType::OnlineBankingFinland + | common_enums::PaymentMethodType::OnlineBankingFpx + | common_enums::PaymentMethodType::OnlineBankingPoland + | common_enums::PaymentMethodType::OnlineBankingSlovakia + | common_enums::PaymentMethodType::Oxxo + | common_enums::PaymentMethodType::PagoEfectivo + | common_enums::PaymentMethodType::PermataBankTransfer + | common_enums::PaymentMethodType::OpenBankingUk + | common_enums::PaymentMethodType::PayBright + | common_enums::PaymentMethodType::Paypal + | common_enums::PaymentMethodType::Paze + | common_enums::PaymentMethodType::Pix + | common_enums::PaymentMethodType::PaySafeCard + | common_enums::PaymentMethodType::Przelewy24 + | common_enums::PaymentMethodType::Pse + | common_enums::PaymentMethodType::RedCompra + | common_enums::PaymentMethodType::RedPagos + | common_enums::PaymentMethodType::SamsungPay + | common_enums::PaymentMethodType::Sepa + | common_enums::PaymentMethodType::SepaBankTransfer + | common_enums::PaymentMethodType::Sofort + | common_enums::PaymentMethodType::Swish + | common_enums::PaymentMethodType::TouchNGo + | common_enums::PaymentMethodType::Trustly + | common_enums::PaymentMethodType::Twint + | common_enums::PaymentMethodType::UpiCollect + | common_enums::PaymentMethodType::UpiIntent + | common_enums::PaymentMethodType::Venmo + | common_enums::PaymentMethodType::Vipps + | common_enums::PaymentMethodType::Walley + | common_enums::PaymentMethodType::WeChatPay + | common_enums::PaymentMethodType::SevenEleven + | common_enums::PaymentMethodType::Lawson + | common_enums::PaymentMethodType::LocalBankTransfer + | common_enums::PaymentMethodType::InstantBankTransfer + | common_enums::PaymentMethodType::MiniStop + | common_enums::PaymentMethodType::FamilyMart + | common_enums::PaymentMethodType::Seicomart + | common_enums::PaymentMethodType::PayEasy + | common_enums::PaymentMethodType::Mifinity + | common_enums::PaymentMethodType::Fps + | common_enums::PaymentMethodType::DuitNow + | common_enums::PaymentMethodType::PromptPay + | common_enums::PaymentMethodType::VietQr + | common_enums::PaymentMethodType::OpenBankingPIS, + ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { + message: payment_method_type.to_string(), + connector: "klarna", + })), } } PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect {}) => { @@ -664,6 +779,120 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData common_enums::PaymentExperience::RedirectToUrl, common_enums::PaymentMethodType::Klarna, ) => Ok(format!("{endpoint}checkout/v3/orders",)), + #[cfg(feature = "v1")] + ( + common_enums::PaymentExperience::DisplayQrCode + | common_enums::PaymentExperience::DisplayWaitScreen + | common_enums::PaymentExperience::InvokePaymentApp + | common_enums::PaymentExperience::InvokeSdkClient + | common_enums::PaymentExperience::LinkWallet + | common_enums::PaymentExperience::OneClick + | common_enums::PaymentExperience::RedirectToUrl + | common_enums::PaymentExperience::CollectOtp, + common_enums::PaymentMethodType::Ach + | common_enums::PaymentMethodType::Affirm + | common_enums::PaymentMethodType::AfterpayClearpay + | common_enums::PaymentMethodType::Alfamart + | common_enums::PaymentMethodType::AliPay + | common_enums::PaymentMethodType::AliPayHk + | common_enums::PaymentMethodType::Alma + | common_enums::PaymentMethodType::AmazonPay + | common_enums::PaymentMethodType::ApplePay + | common_enums::PaymentMethodType::Atome + | common_enums::PaymentMethodType::Bacs + | common_enums::PaymentMethodType::BancontactCard + | common_enums::PaymentMethodType::Becs + | common_enums::PaymentMethodType::Benefit + | common_enums::PaymentMethodType::Bizum + | common_enums::PaymentMethodType::Blik + | common_enums::PaymentMethodType::Boleto + | common_enums::PaymentMethodType::BcaBankTransfer + | common_enums::PaymentMethodType::BniVa + | common_enums::PaymentMethodType::BriVa + | common_enums::PaymentMethodType::CardRedirect + | common_enums::PaymentMethodType::CimbVa + | common_enums::PaymentMethodType::ClassicReward + | common_enums::PaymentMethodType::Credit + | common_enums::PaymentMethodType::CryptoCurrency + | common_enums::PaymentMethodType::Cashapp + | common_enums::PaymentMethodType::Dana + | common_enums::PaymentMethodType::DanamonVa + | common_enums::PaymentMethodType::Debit + | common_enums::PaymentMethodType::DirectCarrierBilling + | common_enums::PaymentMethodType::Efecty + | common_enums::PaymentMethodType::Eft + | common_enums::PaymentMethodType::Eps + | common_enums::PaymentMethodType::Evoucher + | common_enums::PaymentMethodType::Giropay + | common_enums::PaymentMethodType::Givex + | common_enums::PaymentMethodType::GooglePay + | common_enums::PaymentMethodType::GoPay + | common_enums::PaymentMethodType::Gcash + | common_enums::PaymentMethodType::Ideal + | common_enums::PaymentMethodType::Interac + | common_enums::PaymentMethodType::Indomaret + | common_enums::PaymentMethodType::Klarna + | common_enums::PaymentMethodType::KakaoPay + | common_enums::PaymentMethodType::MandiriVa + | common_enums::PaymentMethodType::Knet + | common_enums::PaymentMethodType::MbWay + | common_enums::PaymentMethodType::MobilePay + | common_enums::PaymentMethodType::Momo + | common_enums::PaymentMethodType::MomoAtm + | common_enums::PaymentMethodType::Multibanco + | common_enums::PaymentMethodType::LocalBankRedirect + | common_enums::PaymentMethodType::OnlineBankingThailand + | common_enums::PaymentMethodType::OnlineBankingCzechRepublic + | common_enums::PaymentMethodType::OnlineBankingFinland + | common_enums::PaymentMethodType::OnlineBankingFpx + | common_enums::PaymentMethodType::OnlineBankingPoland + | common_enums::PaymentMethodType::OnlineBankingSlovakia + | common_enums::PaymentMethodType::Oxxo + | common_enums::PaymentMethodType::PagoEfectivo + | common_enums::PaymentMethodType::PermataBankTransfer + | common_enums::PaymentMethodType::OpenBankingUk + | common_enums::PaymentMethodType::PayBright + | common_enums::PaymentMethodType::Paypal + | common_enums::PaymentMethodType::Paze + | common_enums::PaymentMethodType::Pix + | common_enums::PaymentMethodType::PaySafeCard + | common_enums::PaymentMethodType::Przelewy24 + | common_enums::PaymentMethodType::Pse + | common_enums::PaymentMethodType::RedCompra + | common_enums::PaymentMethodType::RedPagos + | common_enums::PaymentMethodType::SamsungPay + | common_enums::PaymentMethodType::Sepa + | common_enums::PaymentMethodType::SepaBankTransfer + | common_enums::PaymentMethodType::Sofort + | common_enums::PaymentMethodType::Swish + | common_enums::PaymentMethodType::TouchNGo + | common_enums::PaymentMethodType::Trustly + | common_enums::PaymentMethodType::Twint + | common_enums::PaymentMethodType::UpiCollect + | common_enums::PaymentMethodType::UpiIntent + | common_enums::PaymentMethodType::Venmo + | common_enums::PaymentMethodType::Vipps + | common_enums::PaymentMethodType::Walley + | common_enums::PaymentMethodType::WeChatPay + | common_enums::PaymentMethodType::SevenEleven + | common_enums::PaymentMethodType::Lawson + | common_enums::PaymentMethodType::LocalBankTransfer + | common_enums::PaymentMethodType::InstantBankTransfer + | common_enums::PaymentMethodType::MiniStop + | common_enums::PaymentMethodType::FamilyMart + | common_enums::PaymentMethodType::Seicomart + | common_enums::PaymentMethodType::PayEasy + | common_enums::PaymentMethodType::Mifinity + | common_enums::PaymentMethodType::Fps + | common_enums::PaymentMethodType::DuitNow + | common_enums::PaymentMethodType::PromptPay + | common_enums::PaymentMethodType::VietQr + | common_enums::PaymentMethodType::OpenBankingPIS, + ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { + message: payment_method_type.to_string(), + connector: "klarna", + })), + #[cfg(feature = "v2")] ( common_enums::PaymentExperience::DisplayQrCode | common_enums::PaymentExperience::DisplayWaitScreen @@ -697,6 +926,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData | common_enums::PaymentMethodType::CimbVa | common_enums::PaymentMethodType::ClassicReward | common_enums::PaymentMethodType::Credit + | common_enums::PaymentMethodType::Card | common_enums::PaymentMethodType::CryptoCurrency | common_enums::PaymentMethodType::Cashapp | common_enums::PaymentMethodType::Dana diff --git a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs index bc5d10620b7..fdee2022577 100644 --- a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs @@ -1117,11 +1117,20 @@ impl TryFrom<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for PaypalPayments )?; let payment_source = match payment_method_type { + #[cfg(feature = "v1")] enums::PaymentMethodType::Credit | enums::PaymentMethodType::Debit => Ok(Some( PaymentSourceItem::Card(CardRequest::CardVaultStruct(VaultStruct { vault_id: connector_mandate_id.into(), })), )), + #[cfg(feature = "v2")] + enums::PaymentMethodType::Credit + | enums::PaymentMethodType::Debit + | enums::PaymentMethodType::Card => Ok(Some(PaymentSourceItem::Card( + CardRequest::CardVaultStruct(VaultStruct { + vault_id: connector_mandate_id.into(), + }), + ))), enums::PaymentMethodType::Paypal => Ok(Some(PaymentSourceItem::Paypal( PaypalRedirectionRequest::PaypalVaultStruct(VaultStruct { vault_id: connector_mandate_id.into(), diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index dedba889c68..b0037ac45dc 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -288,7 +288,7 @@ impl AmountDetails { let order_tax_amount = match self.skip_external_tax_calculation { common_enums::TaxCalculationOverride::Skip => { self.tax_details.as_ref().and_then(|tax_details| { - tax_details.get_tax_amount(confirm_intent_request.payment_method_subtype) + tax_details.get_tax_amount(Some(confirm_intent_request.payment_method_subtype)) }) } common_enums::TaxCalculationOverride::Calculate => None, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index bff233c2588..d4d86641dc3 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -436,7 +436,7 @@ pub struct PaymentAttempt { /// The reference to the payment at the connector side pub connector_payment_id: Option<String>, /// The payment method subtype for the payment attempt. - pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, + pub payment_method_subtype: storage_enums::PaymentMethodType, /// The authentication type that was applied for the payment attempt. pub authentication_applied: Option<common_enums::AuthenticationType>, /// A reference to the payment at connector side. This is returned by the connector @@ -476,7 +476,7 @@ impl PaymentAttempt { #[cfg(feature = "v2")] pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethodType> { // TODO: check if we can fix this - self.payment_method_subtype + Some(self.payment_method_subtype) } #[cfg(feature = "v1")] @@ -660,7 +660,8 @@ impl PaymentAttempt { .unwrap_or(common_enums::PaymentMethod::Card), payment_method_id: None, connector_payment_id: None, - payment_method_subtype: payment_method_subtype_data, + payment_method_subtype: payment_method_subtype_data + .unwrap_or(common_enums::PaymentMethodType::Credit), authentication_applied: None, external_reference_id: None, payment_method_billing_address, diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs index 3acfdc28505..24f8a919ea8 100644 --- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs @@ -33,7 +33,7 @@ pub struct RevenueRecoveryAttemptData { /// payment method of payment attempt. pub payment_method_type: common_enums::PaymentMethod, /// payment method sub type of the payment attempt. - pub payment_method_sub_type: Option<common_enums::PaymentMethodType>, + pub payment_method_sub_type: common_enums::PaymentMethodType, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. @@ -226,7 +226,7 @@ impl From<&BillingConnectorPaymentsSyncResponse> for RevenueRecoveryAttemptData transaction_created_at: data.transaction_created_at, status: data.status, payment_method_type: data.payment_method_type, - payment_method_sub_type: Some(data.payment_method_sub_type), + payment_method_sub_type: data.payment_method_sub_type, network_advice_code: None, network_decline_code: None, network_error_message: None, diff --git a/crates/kgraph_utils/Cargo.toml b/crates/kgraph_utils/Cargo.toml index ac14087c080..6e58f031718 100644 --- a/crates/kgraph_utils/Cargo.toml +++ b/crates/kgraph_utils/Cargo.toml @@ -9,7 +9,7 @@ license.workspace = true [features] dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector"] v1 = ["api_models/v1", "common_utils/v1", "common_types/v1"] -v2 = ["api_models/v2", "common_utils/v2", "common_types/v2"] +v2 = ["api_models/v2", "common_utils/v2", "common_types/v2", "common_enums/v2"] [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" } diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index abaa9df5633..64b79d1563e 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -24,6 +24,8 @@ fn get_dir_value_payment_method( api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)), api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)), api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)), + #[cfg(feature = "v2")] + api_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)), api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 14ff7284536..93e4f8e0408 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -133,6 +133,8 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)), api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)), api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)), + #[cfg(feature = "v2")] + api_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)), api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 548a24b8e32..0eae31ace87 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -33,7 +33,7 @@ payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors payout_retry = ["payouts"] recon = ["email", "api_models/recon"] retry = [] -v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","refunds_v2","scheduler/v2"] +v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","refunds_v2","scheduler/v2","euclid/v2"] v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1","scheduler/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 183ed6adde5..14dc0ec3625 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -691,6 +691,8 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { match value { enums::PaymentMethodType::Credit => Ok(Self::Card), enums::PaymentMethodType::Debit => Ok(Self::Card), + #[cfg(feature = "v2")] + enums::PaymentMethodType::Card => Ok(Self::Card), enums::PaymentMethodType::Klarna => Ok(Self::Klarna), enums::PaymentMethodType::Affirm => Ok(Self::Affirm), enums::PaymentMethodType::AfterpayClearpay => Ok(Self::AfterpayClearpay), diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index b8fe4e83625..52973805d34 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -713,7 +713,7 @@ pub async fn retrieve_payment_method_with_token( pub(crate) fn get_payment_method_create_request( payment_method_data: &api_models::payments::PaymentMethodData, payment_method_type: storage_enums::PaymentMethod, - payment_method_subtype: Option<storage_enums::PaymentMethodType>, + payment_method_subtype: storage_enums::PaymentMethodType, customer_id: id_type::GlobalCustomerId, billing_address: Option<&api_models::payments::Address>, payment_method_session: Option<&domain::payment_methods::PaymentMethodSession>, @@ -977,7 +977,7 @@ pub async fn create_payment_method_core( None, network_tokenization_resp, Some(req.payment_method_type), - req.payment_method_subtype, + Some(req.payment_method_subtype), ) .await .attach_printable("Unable to create Payment method data")?; diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 0173d36cc45..889525ec6d5 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -244,7 +244,7 @@ pub fn make_dsl_input( }; let payment_method_input = dsl_inputs::PaymentMethodInput { payment_method: Some(payments_dsl_input.payment_attempt.payment_method_type), - payment_method_type: payments_dsl_input.payment_attempt.payment_method_subtype, + payment_method_type: Some(payments_dsl_input.payment_attempt.payment_method_subtype), card_network: payments_dsl_input .payment_method_data .as_ref() diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index eb5b3d88173..20f502521fe 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -284,7 +284,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( session_token: None, enrolled_for_3ds: true, related_transaction_id: None, - payment_method_type: payment_data.payment_attempt.payment_method_subtype, + payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), router_return_url: Some(router_return_url), webhook_url, complete_authorize_url, @@ -607,7 +607,7 @@ pub async fn construct_router_data_for_psync<'a>( capture_method: Some(payment_intent.capture_method), connector_meta: attempt.connector_metadata.clone().expose_option(), sync_type: types::SyncRequestType::SinglePaymentSync, - payment_method_type: attempt.payment_method_subtype, + payment_method_type: Some(attempt.payment_method_subtype), currency: payment_intent.amount_details.currency, // TODO: Get the charges object from feature metadata split_payments: None, @@ -948,7 +948,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( email, customer_name: None, return_url: Some(router_return_url), - payment_method_type: payment_data.payment_attempt.payment_method_subtype, + payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), request_incremental_authorization: matches!( payment_data .payment_intent @@ -1666,7 +1666,7 @@ where created: payment_intent.created_at, payment_method_data, payment_method_type: Some(payment_attempt.payment_method_type), - payment_method_subtype: payment_attempt.payment_method_subtype, + payment_method_subtype: Some(payment_attempt.payment_method_subtype), next_action, connector_transaction_id: payment_attempt.connector_payment_id.clone(), connector_reference_id: None, @@ -1770,7 +1770,7 @@ where payment_method_subtype: self .payment_attempt .as_ref() - .and_then(|attempt| attempt.payment_method_subtype), + .map(|attempt| attempt.payment_method_subtype), connector_transaction_id: self .payment_attempt .as_ref() @@ -2897,7 +2897,7 @@ impl ForeignFrom<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> )), created: pi.created_at, payment_method_type: pa.as_ref().and_then(|p| p.payment_method_type.into()), - payment_method_subtype: pa.as_ref().and_then(|p| p.payment_method_subtype), + payment_method_subtype: pa.as_ref().and_then(|p| p.payment_method_subtype.into()), connector: pa.as_ref().and_then(|p| p.connector.clone()), merchant_connector_id: pa.as_ref().and_then(|p| p.merchant_connector_id.clone()), customer: None, diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index 1465629914d..dc2118efc28 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -401,7 +401,7 @@ impl Action { merchant_reference_id, amount: payment_attempt.get_total_amount(), currency: payment_intent.amount_details.currency, - payment_method_type: payment_attempt.payment_method_subtype, + payment_method_type: Some(payment_attempt.payment_method_subtype), attempt_status: payment_attempt.status, connector_transaction_id: payment_attempt .connector_payment_id diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 4c925b9d467..9c5030a30a0 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -69,15 +69,10 @@ impl PaymentMethodCreateExt for PaymentMethodCreate { impl PaymentMethodCreateExt for PaymentMethodCreate { fn validate(&self) -> RouterResult<()> { utils::when( - !self - .payment_method_subtype - .map(|sub| { - validate_payment_method_type_against_payment_method( - self.payment_method_type, - sub, - ) - }) - .unwrap_or(true), // If payment_method_subtype is None, we assume it to be valid + !validate_payment_method_type_against_payment_method( + self.payment_method_type, + self.payment_method_subtype, + ), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid 'payment_method_type' provided".to_string() diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index c11751c8324..6d529b12809 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -532,6 +532,8 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => { Self::Card } + #[cfg(feature = "v2")] + api_enums::PaymentMethodType::Card => Self::Card, api_enums::PaymentMethodType::Evoucher | api_enums::PaymentMethodType::ClassicReward => Self::Reward, api_enums::PaymentMethodType::Boleto diff --git a/v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/down.sql b/v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/down.sql new file mode 100644 index 00000000000..8022b979316 --- /dev/null +++ b/v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_attempt ALTER COLUMN payment_method_subtype DROP NOT NULL; \ No newline at end of file diff --git a/v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/up.sql b/v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/up.sql new file mode 100644 index 00000000000..36985b01119 --- /dev/null +++ b/v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_attempt ALTER COLUMN payment_method_subtype SET NOT NULL; \ No newline at end of file
2025-03-28T07:23:53Z
## 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 --> - Made `payment_method_subtype` mandatory in API endpoints and `payment_attempt` table - Added `card` as an enum variant to `payment_method_subtype` ### Additional Changes - [x] 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 #7661 ## 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 a. Payments Confirm: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195dc22c8487020a9f9ac8bdd908444/confirm-intent' \ --header 'x-client-secret: 12345_pay_0195dc22c8487020a9f9ac8bdd908444_secret_0195dc22c85a7fd1abafa610be7e4283' \ --header 'x-profile-id: pro_6OCXkR6tTttf6LSf4QgA' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_a04e14a10c8248e39702ce55495f6f37' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "card" }' ``` 1 b. Response: ```json { "id": "12345_pay_0195dc22c8487020a9f9ac8bdd908444", "status": "requires_capture", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 100, "amount_captured": 0 }, "customer_id": null, "connector": "stripe", "client_secret": "12345_pay_0195dc22c8487020a9f9ac8bdd908444_secret_0195dc22c85a7fd1abafa610be7e4283", "created": "2025-03-28T09:43:41.914Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "card", "connector_transaction_id": "pi_3R7ZSCD5R7gDAGff1GOVPQmk", "connector_reference_id": null, "merchant_connector_id": "mca_0ipbZpwoLJD7mvBnOfRc", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": { "token": "pm_1R7ZSCD5R7gDAGff0PF9Bz36", "connector_token_request_reference_id": "W8rKh8W3jxvCYXJsgx" }, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds" } ``` 2 a. MCA Create: ``` curl --location 'http://localhost:8080/v2/connector-accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: cloth_seller_7TzDJFNeUNemd0txXfdx' \ --header 'x-profile-id: pro_6OCXkR6tTttf6LSf4QgA' \ --header 'Authorization: admin-api-key=test_admin' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "REDACTED" }, "payment_methods_enabled": [ { "payment_method_type": "card_redirect", "payment_method_subtypes": [ { "payment_method_subtype": "card_redirect", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method_type": "card", "payment_method_subtypes": [ { "payment_method_subtype": "card", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_subtype": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, ... ] } ], "metadata": { "status_url": "https://2753-2401-4900-1cb8-2ff9-24dd-1ccf-ed12-b464.in.ngrok.io/webhooks/merchant_1678699058/globalpay", "account_name": "transaction_processing", "pricing_type": "fixed_price", "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" }, "frm_configs": null, "connector_webhook_details": { "merchant_secret": "" }, "profile_id": "pro_6OCXkR6tTttf6LSf4QgA" }' ``` 2 b. Response: ```json { "connector_type": "payment_processor", "connector_name": "stripe", "connector_label": "stripe_business", "id": "mca_0ipbZpwoLJD7mvBnOfRc", "profile_id": "pro_6OCXkR6tTttf6LSf4QgA", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "REDACTED" }, "payment_methods_enabled": [ { "payment_method_type": "card_redirect", "payment_method_subtypes": [ { "payment_method_subtype": "card_redirect", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method_type": "card", "payment_method_subtypes": [ { "payment_method_subtype": "card", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_subtype": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": -1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, ... ], "connector_webhook_details": { "merchant_secret": "", "additional_secret": null }, "metadata": { "status_url": "https://2753-2401-4900-1cb8-2ff9-24dd-1ccf-ed12-b464.in.ngrok.io/webhooks/merchant_1678699058/globalpay", "account_name": "transaction_processing", "acquirer_bin": "438309", "pricing_type": "fixed_price", "acquirer_merchant_id": "00002000000" }, "disabled": false, "frm_configs": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null, "feature_metadata": null } ``` ## 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.113.0
bd32dd4f0f259336f004a2358a7771652a3c6689
bd32dd4f0f259336f004a2358a7771652a3c6689
juspay/hyperswitch
juspay__hyperswitch-7644
Bug: update(ci): update S3 Source File Name in Postman Collection Runner Workflow The S3 source file name in the Postman Collection Runner workflow needs to be updated due to changes in the Connector Auth File. This modification ensures that the correct file is referenced in CI/CD workflows, maintaining authentication integrity.
2025-03-26T08:11:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [x] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> The S3 Source File Name in Postman Collection Runner Workflow has been changed because the Connector Auth File has been updated. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The connector auth file has been updated, so updating the S3 source file name is required. ## How can we test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Stripe Test cases on Jenkins should pass. ## 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.113.0
617adfa33fd543131b5c4d8983319bfdcaa6c425
617adfa33fd543131b5c4d8983319bfdcaa6c425
juspay/hyperswitch
juspay__hyperswitch-7643
Bug: [Docker] Change user to non-privileged one before running binary We should not be running binary at highest privileges. It is better to not use `app:app` instead.
diff --git a/Dockerfile b/Dockerfile index 4914e6ad235..b2ad0809978 100644 --- a/Dockerfile +++ b/Dockerfile @@ -72,6 +72,10 @@ RUN mkdir -p ${BIN_DIR} COPY --from=builder /router/target/release/${BINARY} ${BIN_DIR}/${BINARY} +# Create the 'app' user and group +RUN useradd --user-group --system --no-create-home --no-log-init app +USER app:app + WORKDIR ${BIN_DIR} CMD ./${BINARY}
2025-03-26T10:33:34Z
## 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 modifies the `Dockerfile` to specify the user at runner stage. ### 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). --> From the security perspective, it is better to be a `user` rather than being a `root`. Closes https://github.com/juspay/hyperswitch/issues/7643 ## 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)? --> build succeeded (tested by making a debug build): ![image](https://github.com/user-attachments/assets/3c27cbe1-56fa-48b9-a4bb-4a5ebb59563c) ```sh podman build \ --load \ --file Dockerfile \ --build-arg "BINARY=router" \ --tag hyperswitch-router \ . ``` ## 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.113.0
4a4284a6961b1c1b32bbff1c2f1cbdd0c60fbf71
4a4284a6961b1c1b32bbff1c2f1cbdd0c60fbf71
juspay/hyperswitch
juspay__hyperswitch-7633
Bug: ProdIntent Changes ProdIntent changes for providing context of product_type and also converting it into merchant-scope from user scope.
diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs index fa550d671fb..8e734d31b53 100644 --- a/crates/api_models/src/user/dashboard_metadata.rs +++ b/crates/api_models/src/user/dashboard_metadata.rs @@ -1,4 +1,4 @@ -use common_enums::CountryAlpha2; +use common_enums::{CountryAlpha2, MerchantProductType}; use common_utils::{id_type, pii}; use masking::Secret; use strum::EnumString; @@ -103,6 +103,8 @@ pub struct ProdIntent { pub poc_contact: Option<String>, pub comments: Option<String>, pub is_completed: bool, + #[serde(default)] + pub product_type: MerchantProductType, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] diff --git a/crates/common_enums/src/enums/accounts.rs b/crates/common_enums/src/enums/accounts.rs index d9c83312d6b..e5b3ef733c6 100644 --- a/crates/common_enums/src/enums/accounts.rs +++ b/crates/common_enums/src/enums/accounts.rs @@ -1,6 +1,7 @@ use serde; use utoipa::ToSchema; #[derive( + Copy, Default, Clone, Debug, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index b9ebdf13028..91b20621da8 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -2974,7 +2974,7 @@ pub async fn list_merchants_for_user_in_org( .map(|merchant_account| user_api::UserMerchantAccountResponse { merchant_name: merchant_account.merchant_name.clone(), merchant_id: merchant_account.get_id().to_owned(), - product_type: merchant_account.product_type.clone(), + product_type: merchant_account.product_type, version: merchant_account.version, }) .collect::<Vec<_>>(), diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index d79d155cba9..a4068fc4fad 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -38,7 +38,6 @@ pub async fn set_metadata( Ok(ApplicationResponse::StatusOk) } -#[cfg(feature = "v1")] pub async fn get_multiple_metadata( state: SessionState, user: UserFromToken, @@ -462,7 +461,7 @@ async fn insert_metadata( pii::Email::from_str(inner_poc_email) .change_context(UserErrors::EmailParsingError)?; } - let mut metadata = utils::insert_user_scoped_metadata_to_db( + let mut metadata = utils::insert_merchant_scoped_metadata_to_db( state, user.user_id.clone(), user.merchant_id.clone(), @@ -473,7 +472,7 @@ async fn insert_metadata( .await; if utils::is_update_required(&metadata) { - metadata = utils::update_user_scoped_metadata( + metadata = utils::update_merchant_scoped_metadata( state, user.user_id.clone(), user.merchant_id.clone(), @@ -500,7 +499,6 @@ async fn insert_metadata( EntityType::Merchant, ) .await?; - let email_contents = email_types::BizEmailProd::new( state, data, @@ -662,7 +660,6 @@ async fn fetch_metadata( Ok(dashboard_metadata) } -#[cfg(feature = "v1")] pub async fn backfill_metadata( state: &SessionState, user: &UserFromToken, @@ -705,6 +702,11 @@ pub async fn backfill_metadata( return Ok(None); }; + #[cfg(feature = "v1")] + let processor_name = mca.connector_name.clone(); + + #[cfg(feature = "v2")] + let processor_name = mca.connector_name.to_string().clone(); Some( insert_metadata( state, @@ -712,13 +714,14 @@ pub async fn backfill_metadata( DBEnum::StripeConnected, types::MetaData::StripeConnected(api::ProcessorConnected { processor_id: mca.get_id(), - processor_name: mca.connector_name, + processor_name, }), ) .await, ) .transpose() } + DBEnum::PaypalConnected => { let mca = if let Some(paypal_connected) = get_merchant_connector_account_by_name( state, @@ -745,6 +748,11 @@ pub async fn backfill_metadata( return Ok(None); }; + #[cfg(feature = "v1")] + let processor_name = mca.connector_name.clone(); + + #[cfg(feature = "v2")] + let processor_name = mca.connector_name.to_string().clone(); Some( insert_metadata( state, @@ -752,7 +760,7 @@ pub async fn backfill_metadata( DBEnum::PaypalConnected, types::MetaData::PaypalConnected(api::ProcessorConnected { processor_id: mca.get_id(), - processor_name: mca.connector_name, + processor_name, }), ) .await, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 2200567ddf9..1879d19de04 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2136,6 +2136,12 @@ impl User { ), ); + route = route.service( + web::resource("/data") + .route(web::get().to(user::get_multiple_dashboard_metadata)) + .route(web::post().to(user::set_dashboard_metadata)), + ); + route } } diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 1af22d0338a..d075048ddb6 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -197,7 +197,6 @@ pub async fn set_dashboard_metadata( .await } -#[cfg(feature = "v1")] pub async fn get_multiple_dashboard_metadata( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/services/email/assets/bizemailprod.html b/crates/router/src/services/email/assets/bizemailprod.html index 3645c953a02..2c973f2d622 100644 --- a/crates/router/src/services/email/assets/bizemailprod.html +++ b/crates/router/src/services/email/assets/bizemailprod.html @@ -104,6 +104,10 @@ <strong>Business Website:</strong> {business_website} </li> + <li> + <strong>Product Type:</strong> + {product_type} + </li> </ol> </td> </tr> diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 5f611bc1b3a..d663f72cec7 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,5 +1,5 @@ use api_models::user::dashboard_metadata::ProdIntent; -use common_enums::EntityType; +use common_enums::{EntityType, MerchantProductType}; use common_utils::{errors::CustomResult, pii, types::theme::EmailThemeConfig}; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; @@ -64,6 +64,7 @@ pub enum EmailBody { legal_business_name: String, business_location: String, business_website: String, + product_type: MerchantProductType, }, ReconActivation { user_name: String, @@ -199,6 +200,7 @@ pub mod html { legal_business_name, business_location, business_website, + product_type, } => { format!( include_str!("assets/bizemailprod.html"), @@ -207,6 +209,7 @@ pub mod html { business_location = business_location, business_website = business_website, username = user_name, + product_type = product_type ) } EmailBody::ProFeatureRequest { @@ -558,6 +561,7 @@ pub struct BizEmailProd { pub settings: std::sync::Arc<configs::Settings>, pub theme_id: Option<String>, pub theme_config: EmailThemeConfig, + pub product_type: MerchantProductType, } impl BizEmailProd { @@ -582,6 +586,7 @@ impl BizEmailProd { business_website: data.business_website.unwrap_or_default(), theme_id, theme_config, + product_type: data.product_type, }) } } @@ -595,6 +600,7 @@ impl EmailData for BizEmailProd { legal_business_name: self.legal_business_name.clone(), business_location: self.business_location.clone(), business_website: self.business_website.clone(), + product_type: self.product_type, }); Ok(EmailContents { diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 4854d1b4786..8bf177035ef 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -417,7 +417,7 @@ impl NewUserMerchant { } pub fn get_product_type(&self) -> Option<common_enums::MerchantProductType> { - self.product_type.clone() + self.product_type } pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> { @@ -703,11 +703,18 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant { } else { id_type::MerchantId::new_from_unix_timestamp() }; + let (user_from_storage, user_merchant_create, user_from_token) = value; Ok(Self { merchant_id, - company_name: Some(UserCompanyName::new(value.1.company_name.clone())?), - product_type: value.1.product_type.clone(), - new_organization: NewUserOrganization::from(value), + company_name: Some(UserCompanyName::new( + user_merchant_create.company_name.clone(), + )?), + product_type: user_merchant_create.product_type, + new_organization: NewUserOrganization::from(( + user_from_storage, + user_merchant_create, + user_from_token, + )), }) } } diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs index c19b52b6f86..a91a3fe917b 100644 --- a/crates/router/src/utils/user/dashboard_metadata.rs +++ b/crates/router/src/utils/user/dashboard_metadata.rs @@ -218,10 +218,9 @@ pub fn separate_metadata_type_based_on_scope( | DBEnum::SetupWoocomWebhook | DBEnum::OnboardingSurvey | DBEnum::IsMultipleConfiguration - | DBEnum::ReconStatus => merchant_scoped.push(key), - DBEnum::Feedback | DBEnum::ProdIntent | DBEnum::IsChangePasswordRequired => { - user_scoped.push(key) - } + | DBEnum::ReconStatus + | DBEnum::ProdIntent => merchant_scoped.push(key), + DBEnum::Feedback | DBEnum::IsChangePasswordRequired => user_scoped.push(key), } } (merchant_scoped, user_scoped)
2025-03-26T09:04:30Z
## 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 introduces support for associating ProdIntent with specific product_types and transitions the feature from being user-scoped to merchant-scoped, enabling more flexible usage across different products. ## Changes Introduced ### 1. New V2 Routes for Dashboard Metadata - Added v2 routes to support `ProdIntent` creation and retrieval with respect to `product_type`. ### 2. Product-Type Context for ProdIntent - While inserting the `ProdIntent` into the `dashboard_metadata` table (for both **v1** and **v2** schemas), the `product_type` is now included in the metadata. ### 3. Merchant-Scoped ProdIntent - **Before:** `ProdIntent` was **user-scoped**, allowing a single request per user. - **Now:** It is **merchant-scoped**, allowing a user to raise separate `ProdIntent` requests for different merchant accounts for each product by the same user. ### 4. Enhanced Email Body - The email body sent for `ProdIntent` now includes the `product_type` context, helping understand for which product the prod intent was raised. ### 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 requesting for Production Access for every product type merchant account. ## 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)? --> Hit the curl: - Dashboard Metadata - ProdIntent (POST): ```bash curl --location 'http://localhost:8080/user/data' \ --header 'accept: */*' \ --header 'accept-language: en-US,en;q=0.9' \ --header 'api-key: hyperswitch' \ --header 'content-type: application/json' \ --header 'origin: https://app.hyperswitch.io' \ --header 'priority: u=1, i' \ --header 'referer: https://app.hyperswitch.io/dashboard/home' \ --header 'sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'sec-fetch-dest: empty' \ --header 'sec-fetch-mode: cors' \ --header 'sec-fetch-site: same-origin' \ --header 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' \ --header 'x-merchant-id: merchant_1715600622' \ --header 'x-profile-id: pro_CqAdpUQBUUam1n0g56mB' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWExMGExMTYtZDc1Ny00MjBlLTkzNWQtZWRlZmQ5ZmQ3NTFmIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQzMDUxMDM3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MzIyMzg0Mywib3JnX2lkIjoib3JnX1h5ZmR4eUttS1RGTEtuNTJ1clBVIiwicHJvZmlsZV9pZCI6InByb190Y3NsZWJDNDhmN1pkNG9mVlRqWCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.NuvkkzrYPcba0JKUUrlM39NfyD2rHZ_jHIkHgPyM39s' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMzcwZWUwYWUtZDI0ZS00ODJhLTlmNDktZDYzYmZkNGE0ZjVhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF9qdmMzb1dXRmxkb0xHNG1GbFc0UCIsInJvbGVfaWQiOiJvcmdfYWRtaW4iLCJleHAiOjE3NDMxMDQxMzcsIm9yZ19pZCI6Im9yZ19hU3NCOWozTWVJcWxVS0YwbDJxRCIsInByb2ZpbGVfaWQiOiJwcm9fcGdrWUkzcnl6TlU2NlBLa3A4ZjciLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.oRERTxTsgrZWNXwSJ5w8CvDHOW1qB2GV3wBQ5Mv-BC8' \ --data-raw '{ "ProdIntent": { "poc_email": "[email protected]", "is_completed": true, "legal_business_name": "blueberry", "business_location": "IN", "business_website": "https://google.com", "poc_name": "berry", "comments": "tx123", "product_type": "orchestration" } }' ``` Dashboard Metadata table should get inserted/updated with the record along with the product_type in the json body. Sample entry to table: <img width="1211" alt="image" src="https://github.com/user-attachments/assets/3312b990-6fcf-4a13-af95-cb63d4e5bb4c" /> Also, product_type should also be sent in the email body to the configured recepient email-id. ![WhatsApp Image 2025-03-28 at 12 58 24 AM](https://github.com/user-attachments/assets/e6082260-70f6-43f0-b71a-7e1b83b50da5) - Dashboard Metadata - ProdIntent (GET): ```bash curl --location 'http://localhost:8080/user/data?keys=ProdIntent' \ --header 'X-Merchant-Id: ddcd_oBuAVsHl0XMLag9JsHCV' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiM2RlMDFhYWYtOWVkMi00YTY5LTg3YWItNWU1YmI2ZWFiNGQ5IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQyMjEyMzQxIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Mjk4MDgyOCwib3JnX2lkIjoib3JnX3pMQmRNTnpLaDZrNmhiT2tockdJIiwicHJvZmlsZV9pZCI6InByb19LWnhHZ21rUHFkMldQdXBFa2psWCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.aD185AZEOcIjHnLnZZ9GJ2ujSHIdRPbPtrYhzNo0V4M' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'Referer: https://integ.hyperswitch.io/dashboard/v2/recon' \ --header 'sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"' \ --header 'X-Profile-Id: pro_UaxaxwTw4A0a9D0QNBrf' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'api-key: hyperswitch' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' ``` Expected Output: ```json [ { "ProdIntent": { "legal_business_name": "blueberry", "business_label": null, "business_location": "IN", "display_name": null, "poc_email": "[email protected]", "business_type": null, "business_identifier": null, "business_website": "https://google.com", "poc_name": "berry", "poc_contact": null, "comments": "tx123", "is_completed": true, "product_type": "orchestration" } } ] ``` Similarly v2 routes: `http://localhost:8080/v2/user/data` (POST) `http://localhost:8080/v2/user/data?keys=ProdIntent` (GET) ## 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.113.0
961c875ecc225c924160448f01bf38a8e5a4ca03
961c875ecc225c924160448f01bf38a8e5a4ca03
juspay/hyperswitch
juspay__hyperswitch-7608
Bug: [FEATURE] [BRAINTREE] Pass connector request reference id ### Feature Description Pass connector request reference id in payment requests to braintree ### Possible Implementation Pass connector request reference id in orderId field in payment requests. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs index 80a62072db2..7f008b24f1a 100644 --- a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs @@ -218,6 +218,7 @@ pub struct RegularTransactionBody { channel: String, #[serde(skip_serializing_if = "Option::is_none")] customer_details: Option<CustomerBody>, + order_id: String, } #[derive(Debug, Serialize)] @@ -228,6 +229,7 @@ pub struct VaultTransactionBody { vault_payment_method_after_transacting: TransactionTiming, #[serde(skip_serializing_if = "Option::is_none")] customer_details: Option<CustomerBody>, + order_id: String, } #[derive(Debug, Serialize)] @@ -268,6 +270,7 @@ impl merchant_account_id: metadata.merchant_account_id, channel: CHANNEL_CODE.to_string(), customer_details: None, + order_id: item.router_data.connector_request_reference_id.clone(), }), ); Ok(Self { @@ -875,6 +878,8 @@ pub struct DataResponse { pub struct RefundInputData { amount: StringMajorUnit, merchant_account_id: Secret<String>, + #[serde(skip_serializing_if = "Option::is_none")] + order_id: Option<String>, } #[derive(Serialize, Debug, Clone)] struct IdFilter { @@ -928,6 +933,7 @@ impl<F> TryFrom<BraintreeRouterData<&RefundsRouterData<F>>> for BraintreeRefundR refund: RefundInputData { amount: item.amount, merchant_account_id: metadata.merchant_account_id, + order_id: item.router_data.refund_id.clone(), }, }, }; @@ -1761,6 +1767,7 @@ impl .get_billing_email() .ok() .map(|email| CustomerBody { email }), + order_id: item.router_data.connector_request_reference_id.clone(), }), ) } else { @@ -1778,6 +1785,7 @@ impl .get_billing_email() .ok() .map(|email| CustomerBody { email }), + order_id: item.router_data.connector_request_reference_id.clone(), }), ) }; @@ -1870,6 +1878,7 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>> .get_billing_email() .ok() .map(|email| CustomerBody { email }), + order_id: item.router_data.connector_request_reference_id.clone(), }), ) } else { @@ -1887,6 +1896,7 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>> .get_billing_email() .ok() .map(|email| CustomerBody { email }), + order_id: item.router_data.connector_request_reference_id.clone(), }), ) };
2025-03-24T12:43:17Z
## 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 connector request reference id in payment requests to braintree ### 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/7608 ## 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)? --> Order ID on braintree dashboard should contain Hyperswitch connector request reference ID for all the transactions: <img width="1618" alt="image" src="https://github.com/user-attachments/assets/63dbd338-ce24-4e45-91bf-99905de22775" /> Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_q0iUEbBtK5AYpgqOXSEq5bha8S9xpSZeZ7HeRzRDZSIVLREPxMnRGOBxEB6mcbjU' \ --data-raw '{ "amount": 100, "currency": "EUR", "confirm": true, "customer_id": "deepanshu", "email": "[email protected]", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5200000000001096", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Deepanshu Bansal", "card_cvc": "123" } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline" }, "billing": { "email": "[email protected]" } }' ``` Response: ``` { "payment_id": "pay_qj6nnKBVA02m4m16Bf0p", "merchant_id": "postman_merchant_GHAction_8dc59add-138a-4366-b2f4-e7fd9a76682e", "status": "requires_customer_action", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 100, "amount_received": null, "connector": "braintree", "client_secret": "pay_qj6nnKBVA02m4m16Bf0p_secret_vp3Dm540FBjEy5oODEu0", "created": "2025-03-24T12:18:19.821Z", "currency": "EUR", "customer_id": "deepanshu", "customer": { "id": "deepanshu", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1096", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "520000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Deepanshu Bansal", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": null, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_qj6nnKBVA02m4m16Bf0p/postman_merchant_GHAction_8dc59add-138a-4366-b2f4-e7fd9a76682e/pay_qj6nnKBVA02m4m16Bf0p_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "deepanshu", "created_at": 1742818699, "expires": 1742822299, "secret": "epk_ece8705d8e4d40f59864e32e6e61727a" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_7Mi4xtmmjuOFZgzb4rqz", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_fQJW054s61taxmNcIf7d", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-24T12:33:19.820Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_0j6JND9oAujfW12x9utN", "payment_method_status": "inactive", "updated": "2025-03-24T12:18:23.369Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "issuer_error_code": null, "issuer_error_message": null } ``` Refunds Request: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_q0iUEbBtK5AYpgqOXSEq5bha8S9xpSZeZ7HeRzRDZSIVLREPxMnRGOBxEB6mcbjU' \ --data '{ "payment_id": "pay_0SDwU6UegcLz7XeOQdPR", "amount": 123, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Refunds Response: ``` { "refund_id": "ref_cqDKR27PsjuksAuU1feK", "payment_id": "pay_0SDwU6UegcLz7XeOQdPR", "amount": 123, "currency": "EUR", "status": "succeeded", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-03-24T12:58:51.627Z", "updated_at": "2025-03-24T12:58:53.214Z", "connector": "braintree", "profile_id": "pro_7Mi4xtmmjuOFZgzb4rqz", "merchant_connector_id": "mca_fQJW054s61taxmNcIf7d", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` <img width="1618" alt="image" src="https://github.com/user-attachments/assets/1243347a-14d1-44bb-8f17-2d045affa523" /> ## 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.113.0
2b70c945406b1cf80831452b75e0c488eb60c86c
2b70c945406b1cf80831452b75e0c488eb60c86c
juspay/hyperswitch
juspay__hyperswitch-7621
Bug: [FEATURE]: Add refunds create core flow for v2 apis. Implement refunds create core flow for v2 apis.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 3125f3ac29c..10682866ab7 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -20357,82 +20357,6 @@ } } }, - "RefundRequest": { - "type": "object", - "required": [ - "payment_id" - ], - "properties": { - "payment_id": { - "type": "string", - "description": "The payment id against which refund is to be initiated", - "example": "pay_mbabizu24mvu3mela5njyhpit4", - "maxLength": 30, - "minLength": 30 - }, - "refund_id": { - "type": "string", - "description": "Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. If this is not passed by the merchant, this field shall be auto generated and provided in the API response. It is recommended to generate uuid(v4) as the refund_id.", - "example": "ref_mbabizu24mvu3mela5njyhpit4", - "nullable": true, - "maxLength": 30, - "minLength": 30 - }, - "merchant_id": { - "type": "string", - "description": "The identifier for the Merchant Account", - "example": "y3oqhf46pyzuxjbcn2giaqnb44", - "nullable": true, - "maxLength": 255 - }, - "amount": { - "type": "integer", - "format": "int64", - "description": "Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the full payment amount", - "example": 6540, - "nullable": true, - "minimum": 100 - }, - "reason": { - "type": "string", - "description": "Reason for the refund. Often useful for displaying to users and your customer support executive. In case the payment went through Stripe, this field needs to be passed with one of these enums: `duplicate`, `fraudulent`, or `requested_by_customer`", - "example": "Customer returned the product", - "nullable": true, - "maxLength": 255 - }, - "refund_type": { - "allOf": [ - { - "$ref": "#/components/schemas/RefundType" - } - ], - "default": "Instant", - "nullable": true - }, - "metadata": { - "type": "object", - "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", - "nullable": true - }, - "merchant_connector_details": { - "allOf": [ - { - "$ref": "#/components/schemas/MerchantConnectorDetailsWrap" - } - ], - "nullable": true - }, - "split_refunds": { - "allOf": [ - { - "$ref": "#/components/schemas/SplitRefund" - } - ], - "nullable": true - } - }, - "additionalProperties": false - }, "RefundResponse": { "type": "object", "required": [ @@ -20535,7 +20459,7 @@ }, "RefundType": { "type": "string", - "description": "To indicate whether to refund needs to be instant or scheduled", + "description": "To indicate whether the refund needs to be instant or scheduled", "enum": [ "scheduled", "instant" @@ -20562,7 +20486,8 @@ "RefundsCreateRequest": { "type": "object", "required": [ - "payment_id" + "payment_id", + "merchant_reference_id" ], "properties": { "payment_id": { @@ -20574,11 +20499,17 @@ }, "merchant_reference_id": { "type": "string", - "description": "Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment.", + "description": "Unique Identifier for the Refund given by the Merchant.", "example": "ref_mbabizu24mvu3mela5njyhpit4", + "maxLength": 64, + "minLength": 1 + }, + "merchant_id": { + "type": "string", + "description": "The identifier for the Merchant Account", + "example": "y3oqhf46pyzuxjbcn2giaqnb44", "nullable": true, - "maxLength": 30, - "minLength": 30 + "maxLength": 255 }, "amount": { "type": "integer", diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index f89558e6267..327406c198c 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -17,9 +17,10 @@ olap = [] openapi = ["common_enums/openapi", "olap", "recon", "dummy_connector", "olap"] recon = [] v1 = ["common_utils/v1"] -v2 = ["common_types/v2", "common_utils/v2", "customer_v2"] +v2 = ["common_types/v2", "common_utils/v2", "customer_v2", "refunds_v2"] customer_v2 = ["common_utils/customer_v2"] payment_methods_v2 = ["common_utils/payment_methods_v2"] +refunds_v2 = [] dynamic_routing = [] control_center_theme = ["dep:actix-web", "dep:actix-multipart"] revenue_recovery = [] diff --git a/crates/api_models/src/events/refund.rs b/crates/api_models/src/events/refund.rs index e87ae154471..888918d836e 100644 --- a/crates/api_models/src/events/refund.rs +++ b/crates/api_models/src/events/refund.rs @@ -1,9 +1,13 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; +#[cfg(feature = "v1")] +use crate::refunds::RefundRequest; +#[cfg(feature = "v2")] +use crate::refunds::RefundsCreateRequest; use crate::refunds::{ RefundAggregateResponse, RefundListFilters, RefundListMetaData, RefundListRequest, - RefundListResponse, RefundManualUpdateRequest, RefundRequest, RefundResponse, - RefundUpdateRequest, RefundsRetrieveRequest, + RefundListResponse, RefundManualUpdateRequest, RefundResponse, RefundUpdateRequest, + RefundsRetrieveRequest, }; #[cfg(feature = "v1")] @@ -19,6 +23,13 @@ impl ApiEventMetric for RefundRequest { } } +#[cfg(feature = "v2")] +impl ApiEventMetric for RefundsCreateRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + None + } +} + #[cfg(feature = "v1")] impl ApiEventMetric for RefundResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index ece1edb72bd..e9a7a77592d 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -12,6 +12,7 @@ use crate::{ enums, }; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundRequest { @@ -61,7 +62,7 @@ pub struct RefundRequest { pub split_refunds: Option<common_types::refunds::SplitRefund>, } -#[cfg(feature = "v2")] +#[cfg(all(feature = "v2", feature = "refunds_v2"))] #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundsCreateRequest { @@ -74,14 +75,18 @@ pub struct RefundsCreateRequest { )] pub payment_id: common_utils::id_type::GlobalPaymentId, - /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. + /// Unique Identifier for the Refund given by the Merchant. #[schema( - max_length = 30, - min_length = 30, + max_length = 64, + min_length = 1, example = "ref_mbabizu24mvu3mela5njyhpit4", - value_type = Option<String>, + value_type = String, )] - pub merchant_reference_id: Option<common_utils::id_type::RefundReferenceId>, + pub merchant_reference_id: common_utils::id_type::RefundReferenceId, + + /// The identifier for the Merchant Account + #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)] + pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the amount_captured of the payment #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] @@ -153,6 +158,7 @@ pub struct RefundManualUpdateRequest { pub error_message: Option<String>, } +#[cfg(feature = "v1")] /// To indicate whether to refund needs to be instant or scheduled #[derive( Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, @@ -164,6 +170,18 @@ pub enum RefundType { Instant, } +#[cfg(feature = "v2")] +/// To indicate whether the refund needs to be instant or scheduled +#[derive( + Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, +)] +#[serde(rename_all = "snake_case")] +pub enum RefundType { + Scheduled, + #[default] + Instant, +} + #[cfg(feature = "v1")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundResponse { diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 4b24cf281cb..0dbf026263f 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -1204,6 +1204,14 @@ impl ConnectorTransactionId { } } + /// Implementation for extracting hashed data + pub fn extract_hashed_data(&self) -> Option<String> { + match self { + Self::TxnId(_) => None, + Self::HashedData(src) => Some(src.clone()), + } + } + /// Implementation for retrieving pub fn get_txn_id<'a>( &'a self, diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index cfcbc2bd199..2543ab41461 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -161,6 +161,29 @@ impl PaymentAttempt { .ok_or(report!(DatabaseError::NotFound)) } + #[cfg(feature = "v2")] + pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id( + conn: &PgPooledConn, + payment_id: &common_utils::id_type::GlobalPaymentId, + ) -> StorageResult<Self> { + // perform ordering on the application level instead of database level + generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( + conn, + dsl::payment_id.eq(payment_id.to_owned()).and( + dsl::status + .eq(enums::AttemptStatus::Charged) + .or(dsl::status.eq(enums::AttemptStatus::PartialCharged)), + ), + Some(1), + None, + Some(dsl::modified_at.desc()), + ) + .await? + .into_iter() + .nth(0) + .ok_or(report!(DatabaseError::NotFound)) + } + #[cfg(feature = "v1")] pub async fn find_by_merchant_id_connector_txn_id( conn: &PgPooledConn, diff --git a/crates/diesel_models/src/query/refund.rs b/crates/diesel_models/src/query/refund.rs index adae21c413f..cf42134cab0 100644 --- a/crates/diesel_models/src/query/refund.rs +++ b/crates/diesel_models/src/query/refund.rs @@ -170,4 +170,26 @@ impl Refund { ) .await } + + pub async fn find_by_merchant_id_connector_transaction_id( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + connector_transaction_id: &str, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::< + <Self as HasTable>::Table, + _, + <<Self as HasTable>::Table as Table>::PrimaryKey, + _, + >( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())), + None, + None, + None, + ) + .await + } } diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index 6a40baba9dd..e197bc3c211 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -11,7 +11,6 @@ use crate::enums as storage_enums; use crate::schema::refund; #[cfg(all(feature = "v2", feature = "refunds_v2"))] use crate::schema_v2::refund; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive( Clone, @@ -702,8 +701,65 @@ impl RefundUpdate { ..source } } + + pub fn build_error_update_for_unified_error_and_message( + unified_error_object: (String, String), + refund_error_message: Option<String>, + refund_error_code: Option<String>, + storage_scheme: &storage_enums::MerchantStorageScheme, + ) -> Self { + let (unified_code, unified_message) = unified_error_object; + + Self::ErrorUpdate { + refund_status: Some(storage_enums::RefundStatus::Failure), + refund_error_message, + refund_error_code, + updated_by: storage_scheme.to_string(), + connector_refund_id: None, + processor_refund_data: None, + unified_code: Some(unified_code), + unified_message: Some(unified_message), + } + } + + pub fn build_error_update_for_integrity_check_failure( + integrity_check_failed_fields: String, + connector_refund_id: Option<ConnectorTransactionId>, + storage_scheme: &storage_enums::MerchantStorageScheme, + ) -> Self { + Self::ErrorUpdate { + refund_status: Some(storage_enums::RefundStatus::ManualReview), + refund_error_message: Some(format!( + "Integrity Check Failed! as data mismatched for fields {}", + integrity_check_failed_fields + )), + refund_error_code: Some("IE".to_string()), + updated_by: storage_scheme.to_string(), + connector_refund_id: connector_refund_id.clone(), + processor_refund_data: connector_refund_id.and_then(|x| x.extract_hashed_data()), + unified_code: None, + unified_message: None, + } + } + + pub fn build_refund_update( + connector_refund_id: ConnectorTransactionId, + refund_status: storage_enums::RefundStatus, + storage_scheme: &storage_enums::MerchantStorageScheme, + ) -> Self { + Self::Update { + connector_refund_id: connector_refund_id.clone(), + refund_status, + sent_to_gateway: true, + refund_error_message: None, + refund_arn: "".to_string(), + updated_by: storage_scheme.to_string(), + processor_refund_data: connector_refund_id.extract_hashed_data(), + } + } } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct RefundCoreWorkflow { pub refund_internal_reference_id: String, @@ -713,6 +769,16 @@ pub struct RefundCoreWorkflow { pub processor_transaction_data: Option<String>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] +pub struct RefundCoreWorkflow { + pub refund_id: common_utils::id_type::GlobalRefundId, + pub connector_transaction_id: ConnectorTransactionId, + pub merchant_id: common_utils::id_type::MerchantId, + pub payment_id: common_utils::id_type::GlobalPaymentId, + pub processor_transaction_data: Option<String>, +} + #[cfg(feature = "v1")] impl common_utils::events::ApiEventMetric for Refund { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 90ba708c109..8179fd66581 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -674,6 +674,29 @@ impl PaymentIntent { pub fn get_feature_metadata(&self) -> Option<FeatureMetadata> { self.feature_metadata.clone() } + + pub fn get_optional_customer_id( + &self, + ) -> CustomResult<Option<id_type::CustomerId>, common_utils::errors::ValidationError> { + self.customer_id + .as_ref() + .map(|customer_id| id_type::CustomerId::try_from(customer_id.clone())) + .transpose() + } + + pub fn get_optional_connector_metadata( + &self, + ) -> CustomResult< + Option<api_models::payments::ConnectorMetadata>, + common_utils::errors::ParsingError, + > { + self.connector_metadata + .clone() + .map(|cm| { + cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") + }) + .transpose() + } } #[cfg(feature = "v1")] diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 494950d42c4..69e5064e6e1 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -117,6 +117,15 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, Self::Error>; + #[cfg(feature = "v2")] + async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + payment_id: &id_type::GlobalPaymentId, + storage_scheme: storage_enums::MerchantStorageScheme, + ) -> error_stack::Result<PaymentAttempt, Self::Error>; + #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, @@ -1014,7 +1023,7 @@ impl PaymentAttempt { } pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> { - todo!(); + self.amount_details.surcharge_amount } } diff --git a/crates/openapi/Cargo.toml b/crates/openapi/Cargo.toml index 7e7e5a6fb3c..33c48e2f0ae 100644 --- a/crates/openapi/Cargo.toml +++ b/crates/openapi/Cargo.toml @@ -17,7 +17,7 @@ common_types = { version = "0.1.0", path = "../common_types" } router_env = { version = "0.1.0", path = "../router_env" } [features] -v2 = ["api_models/v2", "api_models/customer_v2", "common_utils/v2", "api_models/payment_methods_v2", "common_utils/payment_methods_v2"] +v2 = ["api_models/v2", "api_models/customer_v2", "common_utils/v2", "api_models/payment_methods_v2", "common_utils/payment_methods_v2", "api_models/refunds_v2"] v1 = ["api_models/v1", "common_utils/v1"] [lints] diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index d2404e1069d..2629b1b8b7d 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -186,7 +186,6 @@ Never share your secret api keys. Keep them guarded and secure. common_types::refunds::SplitRefund, common_types::payments::ConnectorChargeResponseData, common_types::payments::StripeChargeResponseData, - api_models::refunds::RefundRequest, api_models::refunds::RefundsCreateRequest, api_models::refunds::RefundErrorDetails, api_models::refunds::RefundType, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 0eae31ace87..7dfb87c3669 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -39,7 +39,7 @@ customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswit payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"] revenue_recovery =["api_models/revenue_recovery","hyperswitch_interfaces/revenue_recovery","hyperswitch_domain_models/revenue_recovery","hyperswitch_connectors/revenue_recovery"] -refunds_v2 = ["diesel_models/refunds_v2", "storage_impl/refunds_v2"] +refunds_v2 = ["api_models/refunds_v2", "diesel_models/refunds_v2", "storage_impl/refunds_v2"] # Partial Auth # The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request. diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 83c1058b426..e96aa339e9e 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -42,6 +42,9 @@ pub mod poll; pub mod recon; #[cfg(feature = "v1")] pub mod refunds; +#[cfg(feature = "v2")] +pub mod refunds_v2; + pub mod routing; pub mod surcharge_decision_config; #[cfg(feature = "olap")] diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 6e576509a18..649e9ea57a0 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -1,6 +1,3 @@ -pub mod transformers; -pub mod validator; - #[cfg(feature = "olap")] use std::collections::HashMap; @@ -27,7 +24,10 @@ use crate::{ errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt}, payments::{self, access_token, helpers}, refunds::transformers::SplitRefundInput, - utils as core_utils, + utils::{ + self as core_utils, refunds_transformers as transformers, + refunds_validator as validator, + }, }, db, logger, routes::{metrics, SessionState}, diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs new file mode 100644 index 00000000000..7186bb76bff --- /dev/null +++ b/crates/router/src/core/refunds_v2.rs @@ -0,0 +1,840 @@ +use std::str::FromStr; + +use api_models::{enums::Connector, refunds::RefundErrorDetails}; +use common_utils::{id_type, types as common_utils_types}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::router_data::{ErrorResponse, RouterData}; +use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}; +use router_env::{instrument, tracing}; + +use crate::{ + consts, + core::{ + errors::{self, ConnectorErrorExt, StorageErrorExt}, + payments::{self, access_token, helpers}, + utils::{self as core_utils, refunds_validator}, + }, + db, logger, + routes::{metrics, SessionState}, + services, + types::{ + self, + api::{self, refunds}, + domain, + storage::{self, enums}, + transformers::{ForeignFrom, ForeignTryFrom}, + }, + utils, +}; + +#[instrument(skip_all)] +pub async fn refund_create_core( + state: SessionState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + req: refunds::RefundsCreateRequest, +) -> errors::RouterResponse<refunds::RefundResponse> { + let db = &*state.store; + let (payment_intent, payment_attempt, amount); + + payment_intent = db + .find_payment_intent_by_id( + &(&state).into(), + &req.payment_id, + &key_store, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + utils::when( + !(payment_intent.status == enums::IntentStatus::Succeeded + || payment_intent.status == enums::IntentStatus::PartiallyCaptured), + || { + Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { + current_flow: "refund".into(), + field_name: "status".into(), + current_value: payment_intent.status.to_string(), + states: "succeeded, partially_captured".to_string() + }) + .attach_printable("unable to refund for a unsuccessful payment intent")) + }, + )?; + + let captured_amount = payment_intent + .amount_captured + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("amount captured is none in a successful payment")?; + + // Amount is not passed in request refer from payment intent. + amount = req.amount.unwrap_or(captured_amount); + + utils::when(amount <= common_utils_types::MinorUnit::new(0), || { + Err(report!(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "amount".to_string(), + expected_format: "positive integer".to_string() + }) + .attach_printable("amount less than or equal to zero")) + })?; + + payment_attempt = db + .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + &(&state).into(), + &key_store, + &req.payment_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?; + + let global_refund_id = id_type::GlobalRefundId::generate(&state.conf.cell_information.id); + + tracing::Span::current().record("global_refund_id", global_refund_id.get_string_repr()); + + Box::pin(validate_and_create_refund( + &state, + &merchant_account, + &key_store, + &payment_attempt, + &payment_intent, + amount, + req, + global_refund_id, + )) + .await + .map(services::ApplicationResponse::Json) +} + +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +pub async fn trigger_refund_to_gateway( + state: &SessionState, + refund: &storage::Refund, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + payment_attempt: &storage::PaymentAttempt, + payment_intent: &storage::PaymentIntent, +) -> errors::RouterResult<storage::Refund> { + let db = &*state.store; + + let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?; + + let storage_scheme = merchant_account.storage_scheme; + + let mca = db + .find_merchant_connector_account_by_id(&state.into(), &mca_id, key_store) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch merchant connector account")?; + + metrics::REFUND_COUNT.add( + 1, + router_env::metric_attributes!(("connector", mca_id.get_string_repr().to_string())), + ); + + let connector_enum = mca.connector_name; + + let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &connector_enum.to_string(), + api::GetToken::Connector, + Some(mca_id.clone()), + )?; + + refunds_validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?; + + let mut router_data = core_utils::construct_refund_router_data( + state, + connector_enum, + merchant_account, + key_store, + payment_intent, + payment_attempt, + refund, + &mca, + ) + .await?; + + let add_access_token_result = + access_token::add_access_token(state, &connector, merchant_account, &router_data, None) + .await?; + + logger::debug!(refund_router_data=?router_data); + + access_token::update_router_data_with_access_token_result( + &add_access_token_result, + &mut router_data, + &payments::CallConnectorAction::Trigger, + ); + + let connector_response = + call_connector_service(state, &connector, add_access_token_result, router_data).await; + + let refund_update = get_refund_update_object( + state, + &connector, + &storage_scheme, + merchant_account, + &connector_response, + ) + .await; + + let response = match refund_update { + Some(refund_update) => state + .store + .update_refund( + refund.to_owned(), + refund_update, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!( + "Failed while updating refund: refund_id: {}", + refund.id.get_string_repr() + ) + })?, + None => refund.to_owned(), + }; + // Implement outgoing webhooks here + connector_response.to_refund_failed_response()?; + Ok(response) +} + +async fn call_connector_service( + state: &SessionState, + connector: &api::ConnectorData, + add_access_token_result: types::AddAccessTokenResult, + router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, +) -> Result< + RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, + error_stack::Report<errors::ConnectorError>, +> { + if !(add_access_token_result.connector_supports_access_token + && router_data.access_token.is_none()) + { + let connector_integration: services::BoxedRefundConnectorIntegrationInterface< + api::Execute, + types::RefundsData, + types::RefundsResponseData, + > = connector.connector.get_connector_integration(); + services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await + } else { + Ok(router_data) + } +} + +async fn get_refund_update_object( + state: &SessionState, + connector: &api::ConnectorData, + storage_scheme: &enums::MerchantStorageScheme, + merchant_account: &domain::MerchantAccount, + router_data_response: &Result< + RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, + error_stack::Report<errors::ConnectorError>, + >, +) -> Option<storage::RefundUpdate> { + match router_data_response { + // This error is related to connector implementation i.e if no implementation for refunds for that specific connector in HS or the connector does not support refund itself. + Err(err) => get_connector_implementation_error_refund_update(err, *storage_scheme), + Ok(response) => { + let response = perform_integrity_check(response.clone()); + match response.response.clone() { + Err(err) => Some( + get_connector_error_refund_update(state, err, connector, storage_scheme).await, + ), + Ok(refund_response_data) => Some(get_refund_update_for_refund_response_data( + response, + connector, + refund_response_data, + storage_scheme, + merchant_account, + )), + } + } + } +} + +fn get_connector_implementation_error_refund_update( + error: &error_stack::Report<errors::ConnectorError>, + storage_scheme: enums::MerchantStorageScheme, +) -> Option<storage::RefundUpdate> { + Option::<storage::RefundUpdate>::foreign_from((error.current_context(), storage_scheme)) +} + +async fn get_connector_error_refund_update( + state: &SessionState, + err: ErrorResponse, + connector: &api::ConnectorData, + storage_scheme: &enums::MerchantStorageScheme, +) -> storage::RefundUpdate { + let unified_error_object = get_unified_error_and_message(state, &err, connector).await; + + storage::RefundUpdate::build_error_update_for_unified_error_and_message( + unified_error_object, + err.reason.or(Some(err.message)), + Some(err.code), + storage_scheme, + ) +} + +async fn get_unified_error_and_message( + state: &SessionState, + err: &ErrorResponse, + connector: &api::ConnectorData, +) -> (String, String) { + let option_gsm = helpers::get_gsm_record( + state, + Some(err.code.clone()), + Some(err.message.clone()), + connector.connector_name.to_string(), + consts::REFUND_FLOW_STR.to_string(), + ) + .await; + // Note: Some connectors do not have a separate list of refund errors + // In such cases, the error codes and messages are stored under "Authorize" flow in GSM table + // So we will have to fetch the GSM using Authorize flow in case GSM is not found using "refund_flow" + let option_gsm = if option_gsm.is_none() { + helpers::get_gsm_record( + state, + Some(err.code.clone()), + Some(err.message.clone()), + connector.connector_name.to_string(), + consts::AUTHORIZE_FLOW_STR.to_string(), + ) + .await + } else { + option_gsm + }; + + let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()); + let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message); + + match gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref()) { + Some((code, message)) => (code.to_owned(), message.to_owned()), + None => ( + consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(), + consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(), + ), + } +} + +pub fn get_refund_update_for_refund_response_data( + router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, + connector: &api::ConnectorData, + refund_response_data: types::RefundsResponseData, + storage_scheme: &enums::MerchantStorageScheme, + merchant_account: &domain::MerchantAccount, +) -> storage::RefundUpdate { + // match on connector integrity checks + match router_data.integrity_check.clone() { + Err(err) => { + let connector_refund_id = err + .connector_transaction_id + .map(common_utils_types::ConnectorTransactionId::from); + + metrics::INTEGRITY_CHECK_FAILED.add( + 1, + router_env::metric_attributes!( + ("connector", connector.connector_name.to_string()), + ("merchant_id", merchant_account.get_id().clone()), + ), + ); + + storage::RefundUpdate::build_error_update_for_integrity_check_failure( + err.field_names, + connector_refund_id, + storage_scheme, + ) + } + Ok(()) => { + if refund_response_data.refund_status == diesel_models::enums::RefundStatus::Success { + metrics::SUCCESSFUL_REFUND.add( + 1, + router_env::metric_attributes!(( + "connector", + connector.connector_name.to_string(), + )), + ) + } + + let connector_refund_id = common_utils_types::ConnectorTransactionId::from( + refund_response_data.connector_refund_id, + ); + + storage::RefundUpdate::build_refund_update( + connector_refund_id, + refund_response_data.refund_status, + storage_scheme, + ) + } + } +} + +pub fn perform_integrity_check( + mut router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, +) -> RouterData<api::Execute, types::RefundsData, types::RefundsResponseData> { + // Initiating Integrity check + let integrity_result = check_refund_integrity(&router_data.request, &router_data.response); + router_data.integrity_check = integrity_result; + router_data +} + +impl ForeignFrom<(&errors::ConnectorError, enums::MerchantStorageScheme)> + for Option<storage::RefundUpdate> +{ + fn foreign_from( + (from, storage_scheme): (&errors::ConnectorError, enums::MerchantStorageScheme), + ) -> Self { + match from { + errors::ConnectorError::NotImplemented(message) => { + Some(storage::RefundUpdate::ErrorUpdate { + refund_status: Some(enums::RefundStatus::Failure), + refund_error_message: Some( + errors::ConnectorError::NotImplemented(message.to_owned()).to_string(), + ), + refund_error_code: Some("NOT_IMPLEMENTED".to_string()), + updated_by: storage_scheme.to_string(), + connector_refund_id: None, + processor_refund_data: None, + unified_code: None, + unified_message: None, + }) + } + errors::ConnectorError::NotSupported { message, connector } => { + Some(storage::RefundUpdate::ErrorUpdate { + refund_status: Some(enums::RefundStatus::Failure), + refund_error_message: Some(format!( + "{message} is not supported by {connector}" + )), + refund_error_code: Some("NOT_SUPPORTED".to_string()), + updated_by: storage_scheme.to_string(), + connector_refund_id: None, + processor_refund_data: None, + unified_code: None, + unified_message: None, + }) + } + _ => None, + } + } +} + +pub fn check_refund_integrity<T, Request>( + request: &Request, + refund_response_data: &Result<types::RefundsResponseData, ErrorResponse>, +) -> Result<(), common_utils::errors::IntegrityCheckError> +where + T: FlowIntegrity, + Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>, +{ + let connector_refund_id = refund_response_data + .as_ref() + .map(|resp_data| resp_data.connector_refund_id.clone()) + .ok(); + + request.check_integrity(request, connector_refund_id.to_owned()) +} + +// ********************************************** VALIDATIONS ********************************************** + +#[instrument(skip_all)] +#[allow(clippy::too_many_arguments)] +pub async fn validate_and_create_refund( + state: &SessionState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + payment_attempt: &storage::PaymentAttempt, + payment_intent: &storage::PaymentIntent, + refund_amount: common_utils_types::MinorUnit, + req: refunds::RefundsCreateRequest, + global_refund_id: id_type::GlobalRefundId, +) -> errors::RouterResult<refunds::RefundResponse> { + let db = &*state.store; + + let refund_type = req.refund_type.unwrap_or_default(); + + let merchant_reference_id = req.merchant_reference_id; + + let predicate = req + .merchant_id + .as_ref() + .map(|merchant_id| merchant_id != merchant_account.get_id()); + + utils::when(predicate.unwrap_or(false), || { + Err(report!(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "merchant_id".to_string(), + expected_format: "merchant_id from merchant account".to_string() + }) + .attach_printable("invalid merchant_id in request")) + })?; + + let connector_payment_id = payment_attempt.clone().connector_payment_id.ok_or_else(|| { + report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.") + })?; + + let all_refunds = db + .find_refund_by_merchant_id_connector_transaction_id( + merchant_account.get_id(), + &connector_payment_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; + + let currency = payment_intent.amount_details.currency; + + refunds_validator::validate_payment_order_age( + &payment_intent.created_at, + state.conf.refund.max_age, + ) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "created_at".to_string(), + expected_format: format!( + "created_at not older than {} days", + state.conf.refund.max_age, + ), + })?; + + let total_amount_captured = payment_intent + .amount_captured + .unwrap_or(payment_attempt.get_total_amount()); + + refunds_validator::validate_refund_amount( + total_amount_captured.get_amount_as_i64(), + &all_refunds, + refund_amount.get_amount_as_i64(), + ) + .change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?; + + refunds_validator::validate_maximum_refund_against_payment_attempt( + &all_refunds, + state.conf.refund.max_attempts, + ) + .change_context(errors::ApiErrorResponse::MaximumRefundCount)?; + + let connector = payment_attempt + .connector + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("No connector populated in payment attempt")?; + let (connector_transaction_id, processor_transaction_data) = + common_utils_types::ConnectorTransactionId::form_id_and_data(connector_payment_id); + let refund_create_req = storage::RefundNew { + id: global_refund_id, + merchant_reference_id: merchant_reference_id.clone(), + external_reference_id: Some(merchant_reference_id.get_string_repr().to_string()), + payment_id: req.payment_id, + merchant_id: merchant_account.get_id().clone(), + connector_transaction_id, + connector, + refund_type: enums::RefundType::foreign_from(req.refund_type.unwrap_or_default()), + total_amount: payment_attempt.get_total_amount(), + refund_amount, + currency, + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + refund_status: enums::RefundStatus::Pending, + metadata: req.metadata, + description: req.reason.clone(), + attempt_id: payment_attempt.id.clone(), + refund_reason: req.reason, + profile_id: Some(payment_intent.profile_id.clone()), + connector_id: payment_attempt.merchant_connector_id.clone(), + charges: None, + split_refunds: None, + connector_refund_id: None, + sent_to_gateway: Default::default(), + refund_arn: None, + updated_by: Default::default(), + organization_id: merchant_account.organization_id.clone(), + processor_transaction_data, + processor_refund_data: None, + }; + + let refund = match db + .insert_refund(refund_create_req, merchant_account.storage_scheme) + .await + { + Ok(refund) => { + Box::pin(schedule_refund_execution( + state, + refund.clone(), + refund_type, + merchant_account, + key_store, + payment_attempt, + payment_intent, + )) + .await? + } + Err(err) => { + if err.current_context().is_db_unique_violation() { + Err(errors::ApiErrorResponse::DuplicateRefundRequest)? + } else { + Err(err) + .change_context(errors::ApiErrorResponse::RefundFailed { data: None }) + .attach_printable("Failed to insert refund")? + } + } + }; + + let unified_translated_message = + match (refund.unified_code.clone(), refund.unified_message.clone()) { + (Some(unified_code), Some(unified_message)) => helpers::get_unified_translation( + state, + unified_code, + unified_message.clone(), + state.locale.to_string(), + ) + .await + .or(Some(unified_message)), + _ => refund.unified_message, + }; + + let refund = storage::Refund { + unified_message: unified_translated_message, + ..refund + }; + + api::RefundResponse::foreign_try_from(refund) +} + +impl ForeignTryFrom<storage::Refund> for api::RefundResponse { + type Error = error_stack::Report<errors::ApiErrorResponse>; + fn foreign_try_from(refund: storage::Refund) -> Result<Self, Self::Error> { + let refund = refund; + + let profile_id = refund + .profile_id + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Profile id not found")?; + + let merchant_connector_id = refund + .connector_id + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector id not found")?; + + let connector_name = refund.connector; + let connector = Connector::from_str(&connector_name) + .change_context(errors::ConnectorError::InvalidConnectorName) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| { + format!("unable to parse connector name {connector_name:?}") + })?; + + Ok(Self { + payment_id: refund.payment_id, + id: refund.id.clone(), + amount: refund.refund_amount, + currency: refund.currency, + reason: refund.refund_reason, + status: refunds::RefundStatus::foreign_from(refund.refund_status), + profile_id, + metadata: refund.metadata, + created_at: refund.created_at, + updated_at: refund.modified_at, + connector, + merchant_connector_id, + merchant_reference_id: Some(refund.merchant_reference_id), + error_details: Some(RefundErrorDetails { + code: refund.refund_error_code.unwrap_or_default(), + message: refund.refund_error_message.unwrap_or_default(), + }), + connector_refund_reference_id: None, + }) + } +} + +// ********************************************** PROCESS TRACKER ********************************************** + +#[instrument(skip_all)] +#[allow(clippy::too_many_arguments)] +pub async fn schedule_refund_execution( + state: &SessionState, + refund: storage::Refund, + refund_type: api_models::refunds::RefundType, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + payment_attempt: &storage::PaymentAttempt, + payment_intent: &storage::PaymentIntent, +) -> errors::RouterResult<storage::Refund> { + let db = &*state.store; + let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter; + let task = "EXECUTE_REFUND"; + let task_id = format!("{runner}_{task}_{}", refund.id.get_string_repr()); + + let refund_process = db + .find_process_by_id(&task_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to find the process id")?; + + let result = match refund.refund_status { + enums::RefundStatus::Pending | enums::RefundStatus::ManualReview => { + match (refund.sent_to_gateway, refund_process) { + (false, None) => { + // Execute the refund task based on refund_type + match refund_type { + api_models::refunds::RefundType::Scheduled => { + add_refund_execute_task(db, &refund, runner) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.id.get_string_repr()))?; + + Ok(refund) + } + api_models::refunds::RefundType::Instant => { + let update_refund = Box::pin(trigger_refund_to_gateway( + state, + &refund, + merchant_account, + key_store, + payment_attempt, + payment_intent, + )) + .await; + + match update_refund { + Ok(updated_refund_data) => { + add_refund_sync_task(db, &updated_refund_data, runner) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| format!( + "Failed while pushing refund sync task in scheduler: refund_id: {}", + refund.id.get_string_repr() + ))?; + Ok(updated_refund_data) + } + Err(err) => Err(err), + } + } + } + } + _ => { + // Sync the refund for status check + //[#300]: return refund status response + match refund_type { + api_models::refunds::RefundType::Scheduled => { + add_refund_sync_task(db, &refund, runner) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.id.get_string_repr()))?; + Ok(refund) + } + api_models::refunds::RefundType::Instant => { + // [#255]: This is not possible in schedule_refund_execution as it will always be scheduled + // sync_refund_with_gateway(data, &refund).await + Ok(refund) + } + } + } + } + } + // [#255]: This is not allowed to be otherwise or all + _ => Ok(refund), + }?; + Ok(result) +} + +#[instrument] +pub fn refund_to_refund_core_workflow_model( + refund: &storage::Refund, +) -> storage::RefundCoreWorkflow { + storage::RefundCoreWorkflow { + refund_id: refund.id.clone(), + connector_transaction_id: refund.connector_transaction_id.clone(), + merchant_id: refund.merchant_id.clone(), + payment_id: refund.payment_id.clone(), + processor_transaction_data: refund.processor_transaction_data.clone(), + } +} + +#[instrument(skip_all)] +pub async fn add_refund_execute_task( + db: &dyn db::StorageInterface, + refund: &storage::Refund, + runner: storage::ProcessTrackerRunner, +) -> errors::RouterResult<storage::ProcessTracker> { + let task = "EXECUTE_REFUND"; + let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr()); + let tag = ["REFUND"]; + let schedule_time = common_utils::date_time::now(); + let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + refund_workflow_tracking_data, + None, + schedule_time, + common_types::consts::API_VERSION, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct refund execute process tracker task")?; + + let response = db + .insert_process(process_tracker_entry) + .await + .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) + .attach_printable_lazy(|| { + format!( + "Failed while inserting task in process_tracker: refund_id: {}", + refund.id.get_string_repr() + ) + })?; + Ok(response) +} + +#[instrument(skip_all)] +pub async fn add_refund_sync_task( + db: &dyn db::StorageInterface, + refund: &storage::Refund, + runner: storage::ProcessTrackerRunner, +) -> errors::RouterResult<storage::ProcessTracker> { + let task = "SYNC_REFUND"; + let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr()); + let schedule_time = common_utils::date_time::now(); + let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); + let tag = ["REFUND"]; + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + refund_workflow_tracking_data, + None, + schedule_time, + common_types::consts::API_VERSION, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct refund sync process tracker task")?; + + let response = db + .insert_process(process_tracker_entry) + .await + .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) + .attach_printable_lazy(|| { + format!( + "Failed while inserting task in process_tracker: refund_id: {}", + refund.id.get_string_repr() + ) + })?; + metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "Refund"))); + + Ok(response) +} diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 87dce4ade0b..35901ed8ac3 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -1,6 +1,9 @@ +pub mod refunds_transformers; +pub mod refunds_validator; + use std::{collections::HashSet, marker::PhantomData, str::FromStr}; -use api_models::enums::{DisputeStage, DisputeStatus}; +use api_models::enums::{Connector, DisputeStage, DisputeStatus}; #[cfg(feature = "payouts")] use api_models::payouts::PayoutVendorAccountDetails; use common_enums::{IntentStatus, RequestIncrementalAuthorization}; @@ -16,6 +19,8 @@ use hyperswitch_domain_models::{ merchant_connector_account::MerchantConnectorAccount, payment_address::PaymentAddress, router_data::ErrorResponse, router_request_types, types::OrderDetailsWithAmount, }; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +use masking::ExposeOptionInterface; #[cfg(feature = "payouts")] use masking::{ExposeInterface, PeekInterface}; use maud::{html, PreEscaped}; @@ -232,18 +237,155 @@ pub async fn construct_payout_router_data<'a, F>( #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_refund_router_data<'a, F>( - _state: &'a SessionState, - _connector_id: &str, - _merchant_account: &domain::MerchantAccount, - _key_store: &domain::MerchantKeyStore, - _money: (MinorUnit, enums::Currency), - _payment_intent: &'a storage::PaymentIntent, - _payment_attempt: &storage::PaymentAttempt, - _refund: &'a storage::Refund, - _creds_identifier: Option<String>, - _split_refunds: Option<router_request_types::SplitRefundsRequest>, + state: &'a SessionState, + connector_enum: Connector, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + payment_intent: &'a storage::PaymentIntent, + payment_attempt: &storage::PaymentAttempt, + refund: &'a storage::Refund, + merchant_connector_account: &MerchantConnectorAccount, ) -> RouterResult<types::RefundsRouterData<F>> { - todo!() + let auth_type = merchant_connector_account + .get_connector_account_details() + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + let status = payment_attempt.status; + + let payment_amount = payment_attempt.get_total_amount(); + let currency = payment_intent.amount_details.currency; + + let payment_method_type = payment_attempt.payment_method_type; + + let merchant_connector_account_id = &merchant_connector_account.id; + + let webhook_url = Some(helpers::create_webhook_url( + &state.base_url.clone(), + merchant_account.get_id(), + merchant_connector_account_id.get_string_repr(), + )); + + let supported_connector = &state + .conf + .multiple_api_version_supported_connectors + .supported_connectors; + + let connector_api_version = if supported_connector.contains(&connector_enum) { + state + .store + .find_config_by_key(&format!("connector_api_version_{connector_enum}")) + .await + .map(|value| value.config) + .ok() + } else { + None + }; + + let browser_info = payment_attempt + .browser_info + .clone() + .map(types::BrowserInformation::from); + + let connector_refund_id = refund.get_optional_connector_refund_id().cloned(); + let capture_method = payment_intent.capture_method; + + let customer_id = payment_intent + .get_optional_customer_id() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get optional customer id")?; + + let braintree_metadata = payment_intent + .get_optional_connector_metadata() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed parsing ConnectorMetadata")? + .and_then(|cm| cm.braintree); + + let merchant_account_id = braintree_metadata + .as_ref() + .and_then(|braintree| braintree.merchant_account_id.clone()); + + let merchant_config_currency = + braintree_metadata.and_then(|braintree| braintree.merchant_config_currency); + + let router_data = types::RouterData { + flow: PhantomData, + merchant_id: merchant_account.get_id().clone(), + customer_id, + tenant_id: state.tenant.tenant_id.clone(), + connector: connector_enum.to_string(), + payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), + attempt_id: payment_attempt.id.get_string_repr().to_string().clone(), + status, + payment_method: payment_method_type, + connector_auth_type: auth_type, + description: None, + // Does refund need shipping/billing address ? + address: PaymentAddress::default(), + auth_type: payment_attempt.authentication_type, + connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), + amount_captured: payment_intent + .amount_captured + .map(|amt| amt.get_amount_as_i64()), + payment_method_status: None, + minor_amount_captured: payment_intent.amount_captured, + request: types::RefundsData { + refund_id: refund.id.get_string_repr().to_string(), + connector_transaction_id: refund.get_connector_transaction_id().clone(), + refund_amount: refund.refund_amount.get_amount_as_i64(), + minor_refund_amount: refund.refund_amount, + currency, + payment_amount: payment_amount.get_amount_as_i64(), + minor_payment_amount: payment_amount, + webhook_url, + connector_metadata: payment_attempt.connector_metadata.clone().expose_option(), + reason: refund.refund_reason.clone(), + connector_refund_id: connector_refund_id.clone(), + browser_info, + split_refunds: None, + integrity_object: None, + refund_status: refund.refund_status, + merchant_account_id, + merchant_config_currency, + refund_connector_metadata: refund.metadata.clone(), + capture_method: Some(capture_method), + }, + + response: Ok(types::RefundsResponseData { + connector_refund_id: connector_refund_id.unwrap_or_default(), + refund_status: refund.refund_status, + }), + access_token: None, + session_token: None, + reference_id: None, + payment_method_token: None, + connector_customer: None, + recurring_mandate_payment_data: None, + preprocessing_id: None, + connector_request_reference_id: refund.id.get_string_repr().to_string().clone(), + #[cfg(feature = "payouts")] + payout_method_data: None, + #[cfg(feature = "payouts")] + quote_id: None, + test_mode: None, + payment_method_balance: None, + connector_api_version, + connector_http_status_code: None, + external_latency: None, + apple_pay_flow: None, + frm_metadata: None, + refund_id: Some(refund.id.get_string_repr().to_string().clone()), + dispute_id: None, + connector_response: None, + integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, + connector_mandate_request_reference_id: None, + authentication_id: None, + psd2_sca_exemption_type: None, + }; + + Ok(router_data) } #[cfg(feature = "v1")] @@ -309,7 +451,7 @@ pub async fn construct_refund_router_data<'a, F>( .conf .multiple_api_version_supported_connectors .supported_connectors; - let connector_enum = api_models::enums::Connector::from_str(connector_id) + let connector_enum = Connector::from_str(connector_id) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", @@ -485,7 +627,7 @@ pub fn validate_uuid(uuid: String, key: &str) -> Result<String, errors::ApiError #[cfg(feature = "v1")] pub fn get_split_refunds( - split_refund_input: super::refunds::transformers::SplitRefundInput, + split_refund_input: refunds_transformers::SplitRefundInput, ) -> RouterResult<Option<router_request_types::SplitRefundsRequest>> { match split_refund_input.split_payment_request.as_ref() { Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(stripe_payment)) => { @@ -515,7 +657,7 @@ pub fn get_split_refunds( }; if let Some(charge_id) = charge_id_option { - let options = super::refunds::validator::validate_stripe_charge_refund( + let options = refunds_validator::validate_stripe_charge_refund( charge_type_option, &split_refund_input.refund_request, )?; @@ -543,7 +685,7 @@ pub fn get_split_refunds( split_refund_request, )) = split_refund_input.refund_request.clone() { - super::refunds::validator::validate_adyen_charge_refund( + refunds_validator::validate_adyen_charge_refund( adyen_split_payment_response, &split_refund_request, )?; @@ -573,7 +715,7 @@ pub fn get_split_refunds( split_refund_request, )), ) => { - let user_id = super::refunds::validator::validate_xendit_charge_refund( + let user_id = refunds_validator::validate_xendit_charge_refund( xendit_split_payment_response, split_refund_request, )?; @@ -1472,7 +1614,7 @@ pub async fn validate_and_get_business_profile( } fn connector_needs_business_sub_label(connector_name: &str) -> bool { - let connectors_list = [api_models::enums::Connector::Cybersource]; + let connectors_list = [Connector::Cybersource]; connectors_list .map(|connector| connector.to_string()) .contains(&connector_name.to_string()) diff --git a/crates/router/src/core/refunds/transformers.rs b/crates/router/src/core/utils/refunds_transformers.rs similarity index 100% rename from crates/router/src/core/refunds/transformers.rs rename to crates/router/src/core/utils/refunds_transformers.rs diff --git a/crates/router/src/core/refunds/validator.rs b/crates/router/src/core/utils/refunds_validator.rs similarity index 90% rename from crates/router/src/core/refunds/validator.rs rename to crates/router/src/core/utils/refunds_validator.rs index 573543dfbf7..5f982388264 100644 --- a/crates/router/src/core/refunds/validator.rs +++ b/crates/router/src/core/utils/refunds_validator.rs @@ -110,6 +110,7 @@ pub fn validate_refund_list(limit: Option<i64>) -> CustomResult<i64, errors::Api } } +#[cfg(feature = "v1")] pub fn validate_for_valid_refunds( payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, connector: api_models::enums::Connector, @@ -146,6 +147,38 @@ pub fn validate_for_valid_refunds( } } +#[cfg(feature = "v2")] +pub fn validate_for_valid_refunds( + payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, + connector: api_models::enums::Connector, +) -> RouterResult<()> { + let payment_method_type = payment_attempt.payment_method_type; + + match payment_method_type { + diesel_models::enums::PaymentMethod::PayLater + | diesel_models::enums::PaymentMethod::Wallet => { + let payment_method_subtype = payment_attempt.payment_method_subtype; + + utils::when( + matches!( + (connector, payment_method_subtype), + ( + api_models::enums::Connector::Braintree, + diesel_models::enums::PaymentMethodType::Paypal, + ) + ), + || { + Err(errors::ApiErrorResponse::RefundNotPossible { + connector: connector.to_string(), + } + .into()) + }, + ) + } + _ => Ok(()), + } +} + pub fn validate_stripe_charge_refund( charge_type_option: Option<api_enums::PaymentChargeType>, split_refund_request: &Option<common_types::refunds::SplitRefund>, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 866df70e69b..304428ca141 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1721,6 +1721,24 @@ impl PaymentAttemptInterface for KafkaStore { .await } + #[cfg(feature = "v2")] + async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &domain::MerchantKeyStore, + payment_id: &id_type::GlobalPaymentId, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { + self.diesel_store + .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + key_manager_state, + merchant_key_store, + payment_id, + storage_scheme, + ) + .await + } + #[cfg(feature = "v1")] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, @@ -2759,7 +2777,6 @@ impl RefundInterface for KafkaStore { Ok(refund) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &id_type::MerchantId, diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 211f8ddbc48..fbbe0a6d159 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -57,7 +57,6 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -632,6 +631,24 @@ mod storage { } } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[instrument(skip_all)] + async fn find_refund_by_merchant_id_connector_transaction_id( + &self, + merchant_id: &common_utils::id_type::MerchantId, + connector_transaction_id: &str, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage_types::Refund::find_by_merchant_id_connector_transaction_id( + &conn, + merchant_id, + connector_transaction_id, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn update_refund( @@ -1092,7 +1109,6 @@ impl RefundInterface for MockDb { Ok(refund) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index dc7cb1233fa..2b499c882c8 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -154,7 +154,9 @@ pub fn mk_app( #[cfg(all(feature = "v2", feature = "oltp"))] { - server_app = server_app.service(routes::PaymentMethodSession::server(state.clone())); + server_app = server_app + .service(routes::PaymentMethodSession::server(state.clone())) + .service(routes::Refunds::server(state.clone())); } #[cfg(feature = "v1")] diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index 34feb63ea78..03a5589f770 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -44,7 +44,6 @@ pub mod poll; pub mod profiles; #[cfg(feature = "recon")] pub mod recon; -#[cfg(feature = "v1")] pub mod refunds; #[cfg(feature = "olap")] pub mod routing; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index d2d31790914..9dc67be1d2d 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -48,6 +48,8 @@ use super::pm_auth; use super::poll; #[cfg(all(feature = "v2", feature = "revenue_recovery", feature = "oltp"))] use super::recovery_webhooks::*; +#[cfg(all(feature = "oltp", feature = "v2"))] +use super::refunds; #[cfg(feature = "olap")] use super::routing; #[cfg(all(feature = "olap", feature = "v1"))] @@ -1163,6 +1165,17 @@ impl Refunds { } } +#[cfg(all(feature = "v2", feature = "refunds_v2", feature = "oltp"))] +impl Refunds { + pub fn server(state: AppState) -> Scope { + let mut route = web::scope("/v2/refunds").app_data(web::Data::new(state)); + + route = route.service(web::resource("").route(web::post().to(refunds::refunds_create))); + + route + } +} + #[cfg(feature = "payouts")] pub struct Payouts; diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index aa2afa1c329..c4d157d7de4 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -1,16 +1,21 @@ use actix_web::{web, HttpRequest, HttpResponse}; +use common_utils; use router_env::{instrument, tracing, Flow}; use super::app::AppState; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +use crate::core::refunds::*; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +use crate::core::refunds_v2::*; use crate::{ - core::{api_locking, refunds::*}, + core::api_locking, services::{api, authentication as auth, authorization::permissions::Permission}, types::api::refunds, }; - /// Refunds - Create /// /// To create a refund against an already processed payment +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[utoipa::path( post, path = "/refunds", @@ -59,6 +64,41 @@ pub async fn refunds_create( )) .await } + +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::RefundsCreate))] +// #[post("")] +pub async fn refunds_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<refunds::RefundsCreateRequest>, +) -> HttpResponse { + let flow = Flow::RefundsCreate; + + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: auth::AuthenticationData, req, _| { + refund_create_core(state, auth.merchant_account, auth.key_store, req) + }, + auth::auth_type( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::JWTAuth { + permission: Permission::ProfileRefundWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] /// Refunds - Retrieve (GET) /// /// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment @@ -125,6 +165,8 @@ pub async fn refunds_retrieve( )) .await } + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] /// Refunds - Retrieve (POST) /// /// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment @@ -176,6 +218,8 @@ pub async fn refunds_retrieve_with_body( )) .await } + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] /// Refunds - Update /// /// To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields @@ -221,6 +265,12 @@ pub async fn refunds_update( )) .await } + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] /// Refunds - List /// /// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided @@ -236,7 +286,6 @@ pub async fn refunds_update( security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RefundsList))] -#[cfg(feature = "olap")] pub async fn refunds_list( state: web::Data<AppState>, req: HttpRequest, @@ -266,6 +315,11 @@ pub async fn refunds_list( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] /// Refunds - List at profile level /// /// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided @@ -281,7 +335,6 @@ pub async fn refunds_list( security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RefundsList))] -#[cfg(feature = "olap")] pub async fn refunds_list_profile( state: web::Data<AppState>, req: HttpRequest, @@ -316,6 +369,11 @@ pub async fn refunds_list_profile( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] /// Refunds - Filter /// /// To list the refunds filters associated with list of connectors, currencies and payment statuses @@ -331,7 +389,6 @@ pub async fn refunds_list_profile( security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RefundsList))] -#[cfg(feature = "olap")] pub async fn refunds_filter_list( state: web::Data<AppState>, req: HttpRequest, @@ -361,6 +418,11 @@ pub async fn refunds_filter_list( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] /// Refunds - Filter V2 /// /// To list the refunds filters associated with list of connectors, currencies and payment statuses @@ -375,7 +437,6 @@ pub async fn refunds_filter_list( security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))] -#[cfg(feature = "olap")] pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::RefundsFilters; Box::pin(api::server_wrap( @@ -401,6 +462,11 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) - .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] /// Refunds - Filter V2 at profile level /// /// To list the refunds filters associated with list of connectors, currencies and payment statuses @@ -415,7 +481,6 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) - security(("api_key" = [])) )] #[instrument(skip_all, fields(flow = ?Flow::RefundsFilters))] -#[cfg(feature = "olap")] pub async fn get_refunds_filters_profile( state: web::Data<AppState>, req: HttpRequest, @@ -448,8 +513,12 @@ pub async fn get_refunds_filters_profile( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] #[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))] -#[cfg(feature = "olap")] pub async fn get_refunds_aggregates( state: web::Data<AppState>, req: HttpRequest, @@ -480,8 +549,12 @@ pub async fn get_refunds_aggregates( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] #[instrument(skip_all, fields(flow = ?Flow::RefundsManualUpdate))] -#[cfg(feature = "olap")] pub async fn refunds_manual_update( state: web::Data<AppState>, req: HttpRequest, @@ -503,8 +576,12 @@ pub async fn refunds_manual_update( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" +))] #[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))] -#[cfg(feature = "olap")] pub async fn get_refunds_aggregate_profile( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/types/api/refunds.rs b/crates/router/src/types/api/refunds.rs index 7aafe4de152..ff1f192fd45 100644 --- a/crates/router/src/types/api/refunds.rs +++ b/crates/router/src/types/api/refunds.rs @@ -1,6 +1,9 @@ +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +pub use api_models::refunds::RefundRequest; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +pub use api_models::refunds::RefundsCreateRequest; pub use api_models::refunds::{ - RefundRequest, RefundResponse, RefundStatus, RefundType, RefundUpdateRequest, - RefundsRetrieveRequest, + RefundResponse, RefundStatus, RefundType, RefundUpdateRequest, RefundsRetrieveRequest, }; pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync}; pub use hyperswitch_interfaces::api::refunds::{Refund, RefundExecute, RefundSync}; diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 06f98bb26b0..baafc60f316 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -342,4 +342,26 @@ impl PaymentAttemptInterface for MockDb { .cloned() .unwrap()) } + + #[cfg(feature = "v2")] + #[allow(clippy::unwrap_used)] + async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + &self, + _key_manager_state: &KeyManagerState, + _merchant_key_store: &MerchantKeyStore, + payment_id: &id_type::GlobalPaymentId, + _storage_scheme: storage_enums::MerchantStorageScheme, + ) -> CustomResult<PaymentAttempt, StorageError> { + let payment_attempts = self.payment_attempts.lock().await; + + Ok(payment_attempts + .iter() + .find(|payment_attempt| { + payment_attempt.payment_id == *payment_id + && (payment_attempt.status == storage_enums::AttemptStatus::PartialCharged + || payment_attempt.status == storage_enums::AttemptStatus::Charged) + }) + .cloned() + .unwrap()) + } } diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 0156270484c..9720545821b 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -216,6 +216,33 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } + #[cfg(feature = "v2")] + #[instrument(skip_all)] + async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + payment_id: &common_utils::id_type::GlobalPaymentId, + _storage_scheme: MerchantStorageScheme, + ) -> CustomResult<PaymentAttempt, errors::StorageError> { + let conn = pg_connection_read(self).await?; + DieselPaymentAttempt::find_last_successful_or_partially_captured_attempt_by_payment_id( + &conn, payment_id, + ) + .await + .map_err(|er| { + let new_err = diesel_error_to_data_error(*er.current_context()); + er.change_context(new_err) + })? + .convert( + key_manager_state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError) + } + #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( @@ -1050,6 +1077,26 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } + #[cfg(feature = "v2")] + #[instrument(skip_all)] + async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &MerchantKeyStore, + payment_id: &common_utils::id_type::GlobalPaymentId, + storage_scheme: MerchantStorageScheme, + ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { + // Ignoring storage scheme for v2 implementation + self.router_store + .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + key_manager_state, + merchant_key_store, + payment_id, + storage_scheme, + ) + .await + } + #[cfg(feature = "v2")] async fn find_payment_attempt_by_profile_id_connector_transaction_id( &self,
2025-03-25T09:37:59Z
## 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 is a part of v2 implementation of refunds. This PR contains refunds create core flow, i.e we can be able to create refunds for payments in v2. **Important** We are moving `refunds/transformers.rs` and `refunds/validator.rs` to a separate location because of accessibility to both v1 and v2 refund code. ### Additional Changes - [x] 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). --> Merging this PR would add support for creating refunds for payments in v2 apis. ## 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 Payment Intent api call ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'api-key: xyz' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_' \ --header 'Authorization: api-key=xyz' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"automatic", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" } }' ``` - Response from the above call ```json { "id": "12345_pay_0195d13dd6497c12a3b187039fc4b71e", "status": "requires_payment_method", "amount_details": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "12345_pay_0195d13dd6497c12a3b187039fc4b71e_secret_0195d13dd6547a938bfe7b97b36203a5", "profile_id": "pro_TujgCYCsvWvO6YNsRAmC", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "no_three_ds", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "shipping": { "address": { "city": "Karwar", "country": null, "line1": null, "line2": null, "line3": null, "zip": "581301", "state": "Karnataka", "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "customer_id": null, "customer_present": "present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2025-03-26T07:12:25.588Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` - Confirm Intent API call ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195d13dd6497c12a3b187039fc4b71e/confirm-intent' \ --header 'x-client-secret: 12345_pay_0195d13dd6497c12a3b187039fc4b71e_secret_0195d13dd6547a938bfe7b97b36203a5' \ --header 'x-profile-id: pro_TujgCYCsvWvO6YNsRAmC' \ --header 'Content-Type: application/json' \ --header 'Authorization: publishable-key=pk_dev_58559cdf90434adcb0b92eeb6a8b633f,client-secret=12345_pay_0195d13dd6497c12a3b187039fc4b71e_secret_0195d13dd6547a938bfe7b97b36203a5' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "09", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit" }' ``` - Response from the above call ```json { "id": "12345_pay_0195d13dd6497c12a3b187039fc4b71e", "status": "succeeded", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 100 }, "customer_id": null, "connector": "stripe", "client_secret": "12345_pay_0195d13dd6497c12a3b187039fc4b71e_secret_0195d13dd6547a938bfe7b97b36203a5", "created": "2025-03-26T06:57:25.588Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": "pi_3R6ntzD5R7gDAGff0MYUxZFn", "connector_reference_id": null, "merchant_connector_id": "mca_FhEKUEAUdgv7mVCs3A9U", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": { "token": "pm_1R6ntzD5R7gDAGff07DogD0c", "connector_token_request_reference_id": "oMf8ppmFul0oTqI6Zl" }, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds" } ``` - Create refund for a successful payment ``` curl --location 'http://localhost:8080/v2/refunds' \ --header 'X-Profile-Id: pro_TujgCYCsvWvO6YNsRAmC' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_kksGlKY14xNypCzsrJIXFCzL3t2j5kUs7ChmloPryJsdRy2RWYljonzPCxJSDmuZ' \ --data '{ "payment_id":"12345_pay_0195d13dd6497c12a3b187039fc4b71e", "merchant_reference_id":"1742972385", "reason":"Paid by mistake", "metadata":{ "foo":"bar" } }' ``` - Response from the above call ```json { "id": "12345_ref_0195d13dfedb7790bc1a84be825e64d5", "payment_id": "12345_pay_0195d13dd6497c12a3b187039fc4b71e", "merchant_reference_id": "1742972256", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-03-26T06:57:35.993Z", "updated_at": "2025-03-26T06:57:36.981Z", "connector": "stripe", "profile_id": "pro_TujgCYCsvWvO6YNsRAmC", "merchant_connector_id": "mca_FhEKUEAUdgv7mVCs3A9U", "connector_refund_reference_id": "12345_ref_0195d13dfedb7790bc1a84be825e64d5" } ``` - Trying the same refund again will give us this response ```json {"error":{"type":"invalid_request","message":"The refund amount exceeds the amount captured","code":"IR_13"}} ``` - What if the payment was failed and we try to refund it. (Invalid card number in confirm intent call) ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195d142100474c3bcb32e40935e290d/confirm-intent' \ --header 'x-client-secret: 12345_pay_0195d142100474c3bcb32e40935e290d_secret_0195d14210127d30b524ec0e063b3c0a' \ --header 'x-profile-id: pro_TujgCYCsvWvO6YNsRAmC' \ --header 'Content-Type: application/json' \ --header 'Authorization: publishable-key=pk_dev_58559cdf90434adcb0b92eeb6a8b633f,client-secret=12345_pay_0195d142100474c3bcb32e40935e290d_secret_0195d14210127d30b524ec0e063b3c0a' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit" }' ``` - Response from the above call ```json { "id": "12345_pay_0195d142100474c3bcb32e40935e290d", "status": "failed", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "customer_id": null, "connector": "stripe", "client_secret": "12345_pay_0195d142100474c3bcb32e40935e290d_secret_0195d14210127d30b524ec0e063b3c0a", "created": "2025-03-26T07:02:02.514Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": null, "connector_reference_id": null, "merchant_connector_id": "mca_FhEKUEAUdgv7mVCs3A9U", "browser_info": null, "error": { "code": "invalid_expiry_month", "message": "invalid_expiry_month", "unified_code": null, "unified_message": null }, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds" } ``` - Trying to refund failed payment ``` curl --location 'http://localhost:8080/v2/refunds' \ --header 'X-Profile-Id: pro_TujgCYCsvWvO6YNsRAmC' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_kksGlKY14xNypCzsrJIXFCzL3t2j5kUs7ChmloPryJsdRy2RWYljonzPCxJSDmuZ' \ --data '{ "payment_id":"12345_pay_0195d142100474c3bcb32e40935e290d", "merchant_reference_id":"1742972638", "reason":"Paid by mistake", "metadata":{ "foo":"bar" } }' ``` - Response from the above call ```json { "error": { "type": "invalid_request", "message": "This Payment could not be refund because it has a status of failed. The expected state is succeeded, partially_captured", "code": "IR_14" } } ``` Error case responses - Connector NotImplemented Error (501) ``` { "error": { "type": "invalid_request", "message": "get_url method is not implemented", "code": "IR_00" } } ``` - Connector NotSupported Error (400) ``` { "error": { "type": "invalid_request", "message": "Payment method type not supported", "code": "IR_19", "reason": "Refund is not supported by Stripe" } } ``` ## 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.113.0
2067bc352044f00f2c724b4a97f1de0cf599f337
2067bc352044f00f2c724b4a97f1de0cf599f337
juspay/hyperswitch
juspay__hyperswitch-7630
Bug: [FEATURE] Add Facilitapay connector Facilitapay connector is yet another payment processor. Docs: https://sandbox-portal.facilitapay.com/#/docs
diff --git a/config/config.example.toml b/config/config.example.toml index c373cabac05..7ca8c322c3b 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -208,6 +208,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" +facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" @@ -330,6 +331,7 @@ cards = [ "datatrans", "deutschebank", "digitalvirgo", + "facilitapay", "globalpay", "globepay", "gocardless", diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 594c3aea763..cd567d04c97 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -53,6 +53,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" +facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 1d52421f77b..3aa95a95420 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -57,6 +57,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.convergepay.com/VirtualMerchant/" +facilitapay.base_url = "https://api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com" fiuu.base_url = "https://pay.merchant.razer.com/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 8f1b86fc3b0..4383a426f61 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -57,6 +57,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" +facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" diff --git a/config/development.toml b/config/development.toml index a61785cd821..35989e4a02f 100644 --- a/config/development.toml +++ b/config/development.toml @@ -167,6 +167,7 @@ cards = [ "dummyconnector", "ebanx", "elavon", + "facilitapay", "fiserv", "fiservemea", "fiuu", @@ -282,6 +283,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" +facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 0676ffa5e28..50835c6b12e 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -140,6 +140,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" +facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" @@ -255,6 +256,7 @@ cards = [ "dummyconnector", "ebanx", "elavon", + "facilitapay", "fiserv", "fiservemea", "fiuu", diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index b45b3a69799..f53f6d1c49b 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -80,6 +80,7 @@ pub enum RoutableConnectors { Dlocal, Ebanx, Elavon, + // Facilitapay, Fiserv, Fiservemea, Fiuu, @@ -223,6 +224,7 @@ pub enum Connector { Dlocal, Ebanx, Elavon, + // Facilitapay, Fiserv, Fiservemea, Fiuu, @@ -377,13 +379,14 @@ impl Connector { | Self::Cashtocode | Self::Chargebee | Self::Coinbase - |Self::Coingate + | Self::Coingate | Self::Cryptopay | Self::Deutschebank | Self::Digitalvirgo | Self::Dlocal | Self::Ebanx | Self::Elavon + // | Self::Facilitapay | Self::Fiserv | Self::Fiservemea | Self::Fiuu @@ -532,6 +535,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Dlocal => Self::Dlocal, RoutableConnectors::Ebanx => Self::Ebanx, RoutableConnectors::Elavon => Self::Elavon, + // RoutableConnectors::Facilitapay => Self::Facilitapay, RoutableConnectors::Fiserv => Self::Fiserv, RoutableConnectors::Fiservemea => Self::Fiservemea, RoutableConnectors::Fiuu => Self::Fiuu, @@ -640,6 +644,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Dlocal => Ok(Self::Dlocal), Connector::Ebanx => Ok(Self::Ebanx), Connector::Elavon => Ok(Self::Elavon), + // Connector::Facilitapay => Ok(Self::Facilitapay), Connector::Fiserv => Ok(Self::Fiserv), Connector::Fiservemea => Ok(Self::Fiservemea), Connector::Fiuu => Ok(Self::Fiuu), diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 878d6e420c4..2e6e6bf91fc 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -191,6 +191,7 @@ pub struct ConnectorConfig { pub dlocal: Option<ConnectorTomlConfig>, pub ebanx_payout: Option<ConnectorTomlConfig>, pub elavon: Option<ConnectorTomlConfig>, + // pub facilitapay: Option<ConnectorTomlConfig>, pub fiserv: Option<ConnectorTomlConfig>, pub fiservemea: Option<ConnectorTomlConfig>, pub fiuu: Option<ConnectorTomlConfig>, @@ -365,6 +366,7 @@ impl ConnectorConfig { Connector::Dlocal => Ok(connector_data.dlocal), Connector::Ebanx => Ok(connector_data.ebanx_payout), Connector::Elavon => Ok(connector_data.elavon), + // Connector::Facilitapay => Ok(connector_data.facilitapay), Connector::Fiserv => Ok(connector_data.fiserv), Connector::Fiservemea => Ok(connector_data.fiservemea), Connector::Fiuu => Ok(connector_data.fiuu), diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 57fed695df9..93db897bfaf 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -24,6 +24,7 @@ pub mod deutschebank; pub mod digitalvirgo; pub mod dlocal; pub mod elavon; +pub mod facilitapay; pub mod fiserv; pub mod fiservemea; pub mod fiuu; @@ -90,14 +91,14 @@ pub use self::{ checkout::Checkout, coinbase::Coinbase, coingate::Coingate, cryptopay::Cryptopay, ctp_mastercard::CtpMastercard, cybersource::Cybersource, datatrans::Datatrans, deutschebank::Deutschebank, digitalvirgo::Digitalvirgo, dlocal::Dlocal, elavon::Elavon, - fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu, forte::Forte, getnet::Getnet, - globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, helcim::Helcim, hipay::Hipay, - iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, - juspaythreedsserver::Juspaythreedsserver, klarna::Klarna, mifinity::Mifinity, mollie::Mollie, - moneris::Moneris, multisafepay::Multisafepay, nexinets::Nexinets, nexixpay::Nexixpay, - nomupay::Nomupay, noon::Noon, novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, - opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, paypal::Paypal, - paystack::Paystack, payu::Payu, placetopay::Placetopay, powertranz::Powertranz, + facilitapay::Facilitapay, fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu, forte::Forte, + getnet::Getnet, globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, + helcim::Helcim, hipay::Hipay, iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, + jpmorgan::Jpmorgan, juspaythreedsserver::Juspaythreedsserver, klarna::Klarna, + mifinity::Mifinity, mollie::Mollie, moneris::Moneris, multisafepay::Multisafepay, + nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, noon::Noon, novalnet::Novalnet, + nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, + paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, shift4::Shift4, square::Square, stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar, thunes::Thunes, trustpay::Trustpay, tsys::Tsys, diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay.rs new file mode 100644 index 00000000000..3c6d54eedb6 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay.rs @@ -0,0 +1,575 @@ +pub mod transformers; + +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + ConnectorValidation, + }, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks, +}; +use masking::{ExposeInterface, Mask}; +use transformers as facilitapay; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Facilitapay { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Facilitapay { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Facilitapay {} +impl api::PaymentSession for Facilitapay {} +impl api::ConnectorAccessToken for Facilitapay {} +impl api::MandateSetup for Facilitapay {} +impl api::PaymentAuthorize for Facilitapay {} +impl api::PaymentSync for Facilitapay {} +impl api::PaymentCapture for Facilitapay {} +impl api::PaymentVoid for Facilitapay {} +impl api::Refund for Facilitapay {} +impl api::RefundExecute for Facilitapay {} +impl api::RefundSync for Facilitapay {} +impl api::PaymentToken for Facilitapay {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Facilitapay +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Facilitapay +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Facilitapay { + fn id(&self) -> &'static str { + "facilitapay" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + // TODO! Check connector documentation, on which unit they are processing the currency. + // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, + // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.facilitapay.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = facilitapay::FacilitapayAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![( + headers::AUTHORIZATION.to_string(), + auth.api_key.expose().into_masked(), + )]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: facilitapay::FacilitapayErrorResponse = res + .response + .parse_struct("FacilitapayErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.code, + message: response.message, + reason: response.reason, + attempt_status: None, + connector_transaction_id: None, + issuer_error_code: None, + issuer_error_message: None, + }) + } +} + +impl ConnectorValidation for Facilitapay { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Facilitapay { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Facilitapay {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Facilitapay +{ +} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Facilitapay { + fn get_headers( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + + let connector_router_data = facilitapay::FacilitapayRouterData::from((amount, req)); + let connector_req = + facilitapay::FacilitapayPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: facilitapay::FacilitapayPaymentsResponse = res + .response + .parse_struct("Facilitapay PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Facilitapay { + fn get_headers( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { + let response: facilitapay::FacilitapayPaymentsResponse = res + .response + .parse_struct("facilitapay PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Facilitapay { + fn get_headers( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { + let response: facilitapay::FacilitapayPaymentsResponse = res + .response + .parse_struct("Facilitapay PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Facilitapay {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Facilitapay { + fn get_headers( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let refund_amount = utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + + let connector_router_data = facilitapay::FacilitapayRouterData::from((refund_amount, req)); + let connector_req = + facilitapay::FacilitapayRefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .set_body(types::RefundExecuteType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &RefundsRouterData<Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { + let response: facilitapay::RefundResponse = res + .response + .parse_struct("facilitapay RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Facilitapay { + fn get_headers( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .set_body(types::RefundSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { + let response: facilitapay::RefundResponse = res + .response + .parse_struct("facilitapay RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl webhooks::IncomingWebhook for Facilitapay { + fn get_webhook_object_reference_id( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } +} + +impl ConnectorSpecifications for Facilitapay {} diff --git a/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs new file mode 100644 index 00000000000..81c2f752d3b --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs @@ -0,0 +1,228 @@ +use common_enums::enums; +use common_utils::types::StringMinorUnit; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, RefundsRouterData}, +}; +use hyperswitch_interfaces::errors; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::PaymentsAuthorizeRequestData, +}; + +//TODO: Fill the struct with respective fields +pub struct FacilitapayRouterData<T> { + pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> From<(StringMinorUnit, T)> for FacilitapayRouterData<T> { + fn from((amount, item): (StringMinorUnit, T)) -> Self { + //Todo : use utils to convert the amount to the type of amount that a connector accepts + Self { + amount, + router_data: item, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, PartialEq)] +pub struct FacilitapayPaymentsRequest { + amount: StringMinorUnit, + card: FacilitapayCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct FacilitapayCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&FacilitapayRouterData<&PaymentsAuthorizeRouterData>> for FacilitapayPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &FacilitapayRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(req_card) => { + let card = FacilitapayCard { + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.router_data.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.amount.clone(), + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct FacilitapayAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for FacilitapayAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum FacilitapayPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<FacilitapayPaymentStatus> for common_enums::AttemptStatus { + fn from(item: FacilitapayPaymentStatus) -> Self { + match item { + FacilitapayPaymentStatus::Succeeded => Self::Charged, + FacilitapayPaymentStatus::Failed => Self::Failure, + FacilitapayPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct FacilitapayPaymentsResponse { + status: FacilitapayPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: common_enums::AttemptStatus::from(item.response.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct FacilitapayRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&FacilitapayRouterData<&RefundsRouterData<F>>> for FacilitapayRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &FacilitapayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Serialize, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, + //TODO: Review mapping + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + id: String, + status: RefundStatus, +} + +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct FacilitapayErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 734780a3a6d..3ef5cac04ee 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -148,6 +148,7 @@ default_imp_for_authorize_session_token!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -246,6 +247,7 @@ default_imp_for_calculate_tax!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -344,6 +346,7 @@ default_imp_for_session_update!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, @@ -443,7 +446,7 @@ default_imp_for_post_session_tokens!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, - connectors::Square, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Forte, @@ -460,6 +463,7 @@ default_imp_for_post_session_tokens!( connectors::Recurly, connectors::Redsys, connectors::Shift4, + connectors::Square, connectors::Stax, connectors::Stripebilling, connectors::Taxjar, @@ -537,6 +541,7 @@ default_imp_for_complete_authorize!( connectors::Datatrans, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -625,6 +630,7 @@ default_imp_for_incremental_authorization!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -725,6 +731,7 @@ default_imp_for_create_customer!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -819,6 +826,7 @@ default_imp_for_connector_redirect_response!( connectors::Deutschebank, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -904,6 +912,7 @@ default_imp_for_pre_processing_steps!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -996,6 +1005,7 @@ default_imp_for_post_processing_steps!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1097,6 +1107,7 @@ default_imp_for_approve!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1198,6 +1209,7 @@ default_imp_for_reject!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1299,6 +1311,7 @@ default_imp_for_webhook_source_verification!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1398,6 +1411,7 @@ default_imp_for_accept_dispute!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1497,6 +1511,7 @@ default_imp_for_submit_evidence!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1596,6 +1611,7 @@ default_imp_for_defend_dispute!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1704,6 +1720,7 @@ default_imp_for_file_upload!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1796,6 +1813,7 @@ default_imp_for_payouts!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1895,6 +1913,7 @@ default_imp_for_payouts_create!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1996,6 +2015,7 @@ default_imp_for_payouts_retrieve!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2096,6 +2116,7 @@ default_imp_for_payouts_eligibility!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2196,6 +2217,7 @@ default_imp_for_payouts_fulfill!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2296,6 +2318,7 @@ default_imp_for_payouts_cancel!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2398,6 +2421,7 @@ default_imp_for_payouts_quote!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2500,6 +2524,7 @@ default_imp_for_payouts_recipient!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2602,6 +2627,7 @@ default_imp_for_payouts_recipient_account!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2704,6 +2730,7 @@ default_imp_for_frm_sale!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2807,6 +2834,7 @@ default_imp_for_frm_checkout!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2910,6 +2938,7 @@ default_imp_for_frm_transaction!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3013,6 +3042,7 @@ default_imp_for_frm_fulfillment!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3116,6 +3146,7 @@ default_imp_for_frm_record_return!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3214,6 +3245,7 @@ default_imp_for_revoking_mandates!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3314,6 +3346,7 @@ default_imp_for_uas_pre_authentication!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3412,6 +3445,7 @@ default_imp_for_uas_post_authentication!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3511,6 +3545,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3602,6 +3637,7 @@ default_imp_for_connector_request_id!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3695,6 +3731,7 @@ default_imp_for_fraud_check!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3820,6 +3857,7 @@ default_imp_for_connector_authentication!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -3919,6 +3957,7 @@ default_imp_for_uas_authentication!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4018,6 +4057,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4119,6 +4159,7 @@ default_imp_for_additional_revenue_recovery_call!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -4213,6 +4254,7 @@ default_imp_for_revenue_recovery!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 864f9e44986..46ac9073f73 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -237,6 +237,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -339,6 +340,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -436,6 +438,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -538,6 +541,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -639,6 +643,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -741,6 +746,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -853,6 +859,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -957,6 +964,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1061,6 +1069,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1165,6 +1174,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1269,6 +1279,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1373,6 +1384,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1477,6 +1489,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1581,6 +1594,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1685,6 +1699,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1787,6 +1802,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1891,6 +1907,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1995,6 +2012,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2099,6 +2117,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2203,6 +2222,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2307,6 +2327,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2408,6 +2429,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2494,6 +2516,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -2596,6 +2619,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Digitalvirgo, connectors::Dlocal, connectors::Elavon, + connectors::Facilitapay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, diff --git a/crates/hyperswitch_domain_models/src/configs.rs b/crates/hyperswitch_domain_models/src/configs.rs index 811db2cbec6..5256e1a8245 100644 --- a/crates/hyperswitch_domain_models/src/configs.rs +++ b/crates/hyperswitch_domain_models/src/configs.rs @@ -39,6 +39,7 @@ pub struct Connectors { pub dummyconnector: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, + pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 3d8ca2345c4..0c4b4be1793 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -25,25 +25,26 @@ pub use hyperswitch_connectors::connectors::{ coinbase::Coinbase, coingate, coingate::Coingate, cryptopay, cryptopay::Cryptopay, ctp_mastercard, ctp_mastercard::CtpMastercard, cybersource, cybersource::Cybersource, datatrans, datatrans::Datatrans, deutschebank, deutschebank::Deutschebank, digitalvirgo, - digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, elavon, elavon::Elavon, fiserv, - fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, forte, forte::Forte, - getnet, getnet::Getnet, globalpay, globalpay::Globalpay, globepay, globepay::Globepay, - gocardless, gocardless::Gocardless, helcim, helcim::Helcim, hipay, hipay::Hipay, iatapay, - iatapay::Iatapay, inespay, inespay::Inespay, itaubank, itaubank::Itaubank, jpmorgan, - jpmorgan::Jpmorgan, juspaythreedsserver, juspaythreedsserver::Juspaythreedsserver, klarna, - klarna::Klarna, mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris, - moneris::Moneris, multisafepay, multisafepay::Multisafepay, nexinets, nexinets::Nexinets, - nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, noon, noon::Noon, novalnet, - novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, opennode::Opennode, - paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payme, payme::Payme, paypal, paypal::Paypal, - paystack, paystack::Paystack, payu, payu::Payu, placetopay, placetopay::Placetopay, powertranz, - powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, - razorpay::Razorpay, recurly::Recurly, redsys, redsys::Redsys, shift4, shift4::Shift4, square, - square::Square, stax, stax::Stax, stripebilling, stripebilling::Stripebilling, taxjar, - taxjar::Taxjar, thunes, thunes::Thunes, trustpay, trustpay::Trustpay, tsys, tsys::Tsys, - unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, - volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, worldline, worldline::Worldline, - worldpay, worldpay::Worldpay, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, + digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, elavon, elavon::Elavon, facilitapay, + facilitapay::Facilitapay, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, + fiuu::Fiuu, forte, forte::Forte, getnet, getnet::Getnet, globalpay, globalpay::Globalpay, + globepay, globepay::Globepay, gocardless, gocardless::Gocardless, helcim, helcim::Helcim, + hipay, hipay::Hipay, iatapay, iatapay::Iatapay, inespay, inespay::Inespay, itaubank, + itaubank::Itaubank, jpmorgan, jpmorgan::Jpmorgan, juspaythreedsserver, + juspaythreedsserver::Juspaythreedsserver, klarna, klarna::Klarna, mifinity, mifinity::Mifinity, + mollie, mollie::Mollie, moneris, moneris::Moneris, multisafepay, multisafepay::Multisafepay, + nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, noon, + noon::Noon, novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, + opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payme, payme::Payme, + paypal, paypal::Paypal, paystack, paystack::Paystack, payu, payu::Payu, placetopay, + placetopay::Placetopay, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, + rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly::Recurly, redsys, redsys::Redsys, + shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, stripebilling, + stripebilling::Stripebilling, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, trustpay, + trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service, + unified_authentication_service::UnifiedAuthenticationService, volt, volt::Volt, wellsfargo, + wellsfargo::Wellsfargo, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, xendit, + xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, }; #[cfg(feature = "dummy_connector")] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 5056660b6bd..11251cedc4e 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1369,6 +1369,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { elavon::transformers::ElavonAuthType::try_from(self.auth_type)?; Ok(()) } + // api_enums::Connector::Facilitapay => { + // facilitapay::transformers::FacilitapayAuthType::try_from(self.auth_type)?; + // Ok(()) + // } api_enums::Connector::Fiserv => { fiserv::transformers::FiservAuthType::try_from(self.auth_type)?; fiserv::transformers::FiservSessionObject::try_from(self.connector_meta_data)?; diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 3801240864b..4f83abb9c12 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -1963,7 +1963,7 @@ fn handle_post_capture_response( )), _ => { logger::error!( - "Error in post capture_router_data response: {:?}, Current Status: {:?}. Proceeding without updating.", + "Error in post capture_router_data response: {:?}, Current Status: {:?}. Proceeding without updating.", post_capture_router_data.response, post_capture_router_data.status, ); diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 0a7a1f01b44..2b0625319c0 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -391,6 +391,9 @@ impl ConnectorData { enums::Connector::Elavon => { Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new()))) } + // enums::Connector::Facilitapay => { + // Ok(ConnectorEnum::Old(Box::new(connector::Facilitapay))) + // } enums::Connector::Fiserv => { Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new()))) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index ac8ac703f59..847298db98c 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -242,6 +242,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Dlocal => Self::Dlocal, api_enums::Connector::Ebanx => Self::Ebanx, api_enums::Connector::Elavon => Self::Elavon, + // api_enums::Connector::Facilitapay => Self::Facilitapay, api_enums::Connector::Fiserv => Self::Fiserv, api_enums::Connector::Fiservemea => Self::Fiservemea, api_enums::Connector::Fiuu => Self::Fiuu, diff --git a/crates/router/tests/connectors/facilitapay.rs b/crates/router/tests/connectors/facilitapay.rs new file mode 100644 index 00000000000..717eeb916f1 --- /dev/null +++ b/crates/router/tests/connectors/facilitapay.rs @@ -0,0 +1,421 @@ +use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; +use masking::Secret; +use router::types::{self, api, storage::enums}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct FacilitapayTest; +impl ConnectorActions for FacilitapayTest {} +impl utils::Connector for FacilitapayTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Facilitapay; + utils::construct_connector_data_old( + Box::new(Facilitapay::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .facilitapay + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "facilitapay".to_string() + } +} + +static CONNECTOR: FacilitapayTest = FacilitapayTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenarios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 1efefa90bec..018e4220d09 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -34,6 +34,7 @@ mod dlocal; mod dummyconnector; mod ebanx; mod elavon; +mod facilitapay; mod fiserv; mod fiservemea; mod fiuu; @@ -91,7 +92,6 @@ mod taxjar; mod trustpay; mod tsys; mod unified_authentication_service; - mod utils; mod volt; mod wellsfargo; diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 5ce2561af27..c12563303c5 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -41,6 +41,7 @@ pub struct ConnectorAuthentication { pub dummyconnector: Option<HeaderKey>, pub ebanx: Option<HeaderKey>, pub elavon: Option<HeaderKey>, + pub facilitapay: Option<BodyKey>, pub fiserv: Option<SignatureKey>, pub fiservemea: Option<HeaderKey>, pub fiuu: Option<HeaderKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index a468b970666..eac7fb71212 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -106,6 +106,7 @@ dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" +facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" @@ -220,6 +221,7 @@ cards = [ "dummyconnector", "ebanx", "elavon", + "facilitapay", "fiserv", "fiservemea", "fiuu", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 0473e6780dc..75de021f04d 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -6,7 +6,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # Add new connector to existing list and sort it - connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim hipay iatapay inespay itaubank jpmorgan juspaythreedsserver klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys shift4 square stax stripe stripebilling taxjar threedsecureio thunes trustpay tsys unified_authentication_service volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") + connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon facilitapay fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim hipay iatapay inespay itaubank jpmorgan juspaythreedsserver klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys shift4 square stax stripe stripebilling taxjar threedsecureio thunes trustpay tsys unified_authentication_service volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res="$(echo ${sorted[@]})" sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2025-03-25T16:11:16Z
## 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 template code for new connector named `Facilitapay`. Docs: https://sandbox-portal.facilitapay.com/#/docs ### 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` --> YES. 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). --> New connector -- Facilitapay Closes #7630 ## 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)? --> ```sh just clippy cargo +nightly fmt --all cargo c ``` Hyperswitch code base should compile. ## 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` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
60d5c779e9ace4cb95bdbe9a2c9277c41ce96573
60d5c779e9ace4cb95bdbe9a2c9277c41ce96573
juspay/hyperswitch
juspay__hyperswitch-7607
Bug: [BUG] 5xx in PayPal when cancelling the Payment we're getting 5xx when you try to cancel the payment express checkout page. and this is not intended.
diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs index 223be54d3fd..45749332081 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs @@ -187,6 +187,9 @@ pub struct Notifications { /// The merchant URL that will receive the notification when the 3DS ACS successfully gathers /// de ice informatiSon and tonotification_configurations.cordingly. pub three_ds_method_return_url: Option<String>, + /// The URL on merchant's website to which the customer should be redirected in the event of + /// the customer canceling the transaction. + pub cancel_url: Option<String>, } #[derive(Debug, Serialize, Deserialize)] diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs index a5f905d0e70..a36cdc2a53a 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/response.rs @@ -69,7 +69,7 @@ pub struct Action { pub time_created: Option<String>, /// Indicates the action taken. #[serde(rename = "type")] - pub action_type: Option<String>, + pub action_type: Option<ActionType>, } #[derive(Debug, Deserialize, Serialize)] @@ -266,6 +266,35 @@ pub struct ProviderClass { pub enum ResultCode { Declined, Success, + Pending, + Error, +} + +/// Indicates the specific action taken. +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ActionType { + Adjust, + Authorize, + Capture, + Confirm, + Force, + Increment, + Initiate, + MultipleCapture, + Preauthorize, + PreauthorizeMultipleCapturere, + Authorization, + RedirectFrom, + RedirectTo, + Refund, + Hold, + Release, + Reverse, + Split, + StatusNotification, + TransactionList, + TransactionSingle, } /// A string generated by the payment method that represents to what degree the merchant is @@ -335,19 +364,6 @@ pub enum Brand { Visa, } -/// If enabled, this field indicates whether the payment method has been seen before or is -/// new. -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum FingerprintPresenceIndicator { - /// Indicates that the payment method was seen on the platform before by this - /// merchant. - Exists, - /// Indicates that the payment method was not seen on the platform before by this - /// merchant. - New, -} - /// Indicates where a transaction is in its lifecycle. #[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] @@ -389,13 +405,6 @@ pub struct GlobalpayWebhookObjectEventType { pub status: GlobalpayWebhookStatus, } -#[derive(Debug, Deserialize, Serialize)] -pub struct GlobalpayPaymentsWebhookResponse { - pub id: String, - pub account_id: Option<String>, - pub account_name: Option<String>, -} - #[derive(Debug, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum GlobalpayWebhookStatus { @@ -404,8 +413,3 @@ pub enum GlobalpayWebhookStatus { #[serde(other)] Unknown, } - -#[derive(Debug, Serialize, Deserialize)] -pub struct GlobalpayRedirectResponse { - pub status: Option<GlobalpayPaymentStatus>, -} diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs index 24cfa66ef39..124b611d049 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs @@ -116,6 +116,7 @@ impl TryFrom<&GlobalPayRouterData<&PaymentsAuthorizeRouterData>> for GlobalpayPa decoupled_challenge_return_url: None, status_url: item.router_data.request.webhook_url.clone(), three_ds_method_return_url: None, + cancel_url: get_return_url(item.router_data), }), authorization_mode: None, cashback_amount: None, @@ -477,7 +478,14 @@ fn get_return_url(item: &PaymentsAuthorizeRouterData) -> Option<String> { match item.request.payment_method_data.clone() { payment_method_data::PaymentMethodData::Wallet( payment_method_data::WalletData::PaypalRedirect(_), - ) => item.request.complete_authorize_url.clone(), + ) => { + // Return URL handling for PayPal via Globalpay: + // - PayPal inconsistency: Return URLs work with HTTP, but cancel URLs require HTTPS + // - Local development: When testing locally, expose your server via HTTPS and replace + // the base URL with an HTTPS URL to ensure proper cancellation flow + // - Refer to commit 6499d429da87 for more information + item.request.complete_authorize_url.clone() + } _ => item.request.router_return_url.clone(), } } diff --git a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs index 23a0daa45b4..a1fc1bdd828 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs @@ -309,7 +309,7 @@ impl TryFrom<enums::AttemptStatus> for RecurlyRecordStatus { #[derive(Debug, Deserialize, Serialize, Clone)] pub struct RecurlyRecordbackResponse { - // inovice id + // invoice id pub id: id_type::PaymentReferenceId, }
2025-03-24T12:08:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR addresses 5xx that currently is being thrown when a user tries to cancel the PayPal transactions from the redirected page: <img width="372" alt="image" src="https://github.com/user-attachments/assets/4f920b8b-6ab4-4bcb-9705-dc4d15635c2d" /> This is addressed by introducing a new field `cancel_url` that is required for PayPal. This PR also removes unused structs and enums. In addition to that, `ActionType` has been replaced the previous `String` and now that it only accepts limited number of values. ### 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). --> We're getting a 5xx when trying to cancel the payment. Closes [#7607](https://github.com/juspay/hyperswitch/issues/7607) ## 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)? --> ▶ Expose the `localhost` to the internet via `tailscale funnel` <details> <summary>Make a Paypal transaction</summary> Create Payment: ```curl curl --location 'https://pix-mbp.orthrus-monster.ts.net/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_DYcmLTXXQ6gF1HulHKL1WMBpoP8Uw2v1M4eO9mqp9za9AHCpJfhloE568dArpo5Y' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ```json { "payment_id": "pay_nL4QMyfyB3Q6T0Cs2OEf", "merchant_id": "postman_merchant_GHAction_164c761e-166f-4a82-859f-609d96a725b0", "status": "requires_payment_method", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_nL4QMyfyB3Q6T0Cs2OEf_secret_No5MIK8z5xGpdgyfb5gH", "created": "2025-03-24T11:25:08.436Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1742815508, "expires": 1742819108, "secret": "epk_bc69bc123b7446839d02b177bc3273f7" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_bf5d6NP8wcNd1vnsH0eE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-24T11:40:08.436Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-24T11:25:08.461Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "issuer_error_code": null, "issuer_error_message": null } ``` Confirm payment: ```curl curl --location 'https://pix-mbp.orthrus-monster.ts.net/payments/pay_5Vm2zTuuBxSsYrddguto/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_DYcmLTXXQ6gF1HulHKL1WMBpoP8Uw2v1M4eO9mqp9za9AHCpJfhloE568dArpo5Y' \ --data '{ "payment_method": "wallet", "payment_method_type": "paypal", "return_url": "https://nohello.com", "payment_method_data": { "wallet": { "paypal_redirect": { } } } } ' ``` ```json { "payment_id": "pay_nL4QMyfyB3Q6T0Cs2OEf", "merchant_id": "postman_merchant_GHAction_164c761e-166f-4a82-859f-609d96a725b0", "status": "requires_customer_action", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "globalpay", "client_secret": "pay_nL4QMyfyB3Q6T0Cs2OEf_secret_No5MIK8z5xGpdgyfb5gH", "created": "2025-03-24T11:25:08.436Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://nohello.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_nL4QMyfyB3Q6T0Cs2OEf/postman_merchant_GHAction_164c761e-166f-4a82-859f-609d96a725b0/pay_nL4QMyfyB3Q6T0Cs2OEf_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "paypal", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "TRN_PRy15uCj0zyEXanseeWWt78nr53Zh4_Q6T0Cs2OEf_1", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_nL4QMyfyB3Q6T0Cs2OEf_1", "payment_link": null, "profile_id": "pro_bf5d6NP8wcNd1vnsH0eE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_vURZVfOwYJUGEdIvkfny", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-24T11:40:08.436Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "103.159.11.202", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-24T11:25:12.890Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>Click on `Cancel and return to Global Pay Merchant's Test Store` in PayPal **Express Checkout** page</summary> <img width="561" alt="image" src="https://github.com/user-attachments/assets/b13b7e05-31c1-4037-a9b7-a7fd8c2d017f" /> </details> <details> <summary>You should be redirected to the `return_url` with payment status as `failed`</summary> <img width="652" alt="image" src="https://github.com/user-attachments/assets/18aab179-ccce-4ce4-ab83-3a13e970999f" /> </details> <details> <summary>Retrieve the Payment to see the updated status</summary> ```curl curl --location 'https://pix-mbp.orthrus-monster.ts.net/payments/pay_5Vm2zTuuBxSsYrddguto?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_DYcmLTXXQ6gF1HulHKL1WMBpoP8Uw2v1M4eO9mqp9za9AHCpJfhloE568dArpo5Y' ``` ```json { "payment_id": "pay_nL4QMyfyB3Q6T0Cs2OEf", "merchant_id": "postman_merchant_GHAction_164c761e-166f-4a82-859f-609d96a725b0", "status": "failed", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "globalpay", "client_secret": "pay_nL4QMyfyB3Q6T0Cs2OEf_secret_No5MIK8z5xGpdgyfb5gH", "created": "2025-03-24T11:25:08.436Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://nohello.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": "INVALID_REQUEST_DATA", "error_message": "The supplied Payer Id doesn't match the value saved in the database", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "paypal", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": true, "connector_transaction_id": "TRN_PRy15uCj0zyEXanseeWWt78nr53Zh4_Q6T0Cs2OEf_1", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_nL4QMyfyB3Q6T0Cs2OEf_1", "payment_link": null, "profile_id": "pro_bf5d6NP8wcNd1vnsH0eE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_vURZVfOwYJUGEdIvkfny", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-24T11:40:08.436Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "103.159.11.202", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-24T11:25:23.530Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "issuer_error_code": null, "issuer_error_message": null } ``` </details> ## 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.113.0
2b70c945406b1cf80831452b75e0c488eb60c86c
2b70c945406b1cf80831452b75e0c488eb60c86c
juspay/hyperswitch
juspay__hyperswitch-7620
Bug: feat(cypress): `connectorUpdateCall` fails due to fixtures overwrite The `connectorUpdateCall` fails in the Cypress Tests for connectors for which a certain metadata field is `required` (for e.g., `Braintree`) because the `cypress-tests/cypress/fixtures/update-connector-body.json` overwrites the Request Body.
2025-03-25T10:14:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> The Connector Update Body is being overwritten, which included the metadata as well. Due to this, if there were any required metadata fields of a connector, then the Connector Update Test would fail. For example, `Braintree` connector has a required metadata field, and while testing the Connector Update, just because it was being overwritten by the `update-connector-body.json` fixture, the test fails as shown in the following screenshot. <img width="2117" alt="image" src="https://github.com/user-attachments/assets/bf8b384a-92be-4f86-bf09-48fd52f01db4" /> ### 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). --> While adding the Card test Flows for the `Braintree` connector, the Connector Update Test Failed. ## 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)? --> Running the `0000-CoreFlows.cy.js` for `Braintree` connector <img width="2116" alt="image" src="https://github.com/user-attachments/assets/7b505791-4da3-4fae-a94c-142dcfc69b53" /> <img width="752" alt="image" src="https://github.com/user-attachments/assets/f9fc5350-4bf9-4b2e-a5da-a62264f5c1b1" /> ## 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.113.0
00e056800cb2c75c4dfbed6a4451658fda9c4a86
00e056800cb2c75c4dfbed6a4451658fda9c4a86
juspay/hyperswitch
juspay__hyperswitch-7598
Bug: [BUG] [CARD TESTING GUARD] Card Testing Guard Config null value fix for existing profiles ### Bug Description For existing business profiles, the value of card_testing_guard_config appears null ### Expected Behavior For existing business profiles, the value of card_testing_guard_config should not appear null ### Actual Behavior For existing business profiles, the value of card_testing_guard_config appears null ### Steps To Reproduce Retrieve an existing business_profile, and card_testing_guard_config will appear null. ### Context For The Bug _No response_ ### Environment Integ, Sandbox, Production ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 94da0f0438b..ae3706a87d5 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -635,6 +635,25 @@ pub struct CardTestingGuardConfig { common_utils::impl_to_sql_from_sql_json!(CardTestingGuardConfig); +impl Default for CardTestingGuardConfig { + fn default() -> Self { + Self { + is_card_ip_blocking_enabled: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_STATUS, + card_ip_blocking_threshold: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_THRESHOLD, + is_guest_user_card_blocking_enabled: + common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS, + guest_user_card_blocking_threshold: + common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD, + is_customer_id_blocking_enabled: + common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_STATUS, + customer_id_blocking_threshold: + common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD, + card_testing_guard_expiry: + common_utils::consts::DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS, + } + } +} + #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Json)] pub struct WebhookDetails { diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 7bf25e689ab..b889414793d 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3703,26 +3703,10 @@ impl ProfileCreateBridge for api::ProfileCreate { "fs", ))); - let card_testing_guard_config = match self.card_testing_guard_config { - Some(card_testing_guard_config) => Some(CardTestingGuardConfig::foreign_from( - card_testing_guard_config, - )), - None => Some(CardTestingGuardConfig { - is_card_ip_blocking_enabled: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_STATUS, - card_ip_blocking_threshold: - common_utils::consts::DEFAULT_CARD_IP_BLOCKING_THRESHOLD, - is_guest_user_card_blocking_enabled: - common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS, - guest_user_card_blocking_threshold: - common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD, - is_customer_id_blocking_enabled: - common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_STATUS, - customer_id_blocking_threshold: - common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD, - card_testing_guard_expiry: - common_utils::consts::DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS, - }), - }; + let card_testing_guard_config = self + .card_testing_guard_config + .map(CardTestingGuardConfig::foreign_from) + .or(Some(CardTestingGuardConfig::default())); Ok(domain::Profile::from(domain::ProfileSetter { profile_id, @@ -3874,26 +3858,10 @@ impl ProfileCreateBridge for api::ProfileCreate { "fs", ))); - let card_testing_guard_config = match self.card_testing_guard_config { - Some(card_testing_guard_config) => Some(CardTestingGuardConfig::foreign_from( - card_testing_guard_config, - )), - None => Some(CardTestingGuardConfig { - is_card_ip_blocking_enabled: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_STATUS, - card_ip_blocking_threshold: - common_utils::consts::DEFAULT_CARD_IP_BLOCKING_THRESHOLD, - is_guest_user_card_blocking_enabled: - common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS, - guest_user_card_blocking_threshold: - common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD, - is_customer_id_blocking_enabled: - common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_STATUS, - customer_id_blocking_threshold: - common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD, - card_testing_guard_expiry: - common_utils::consts::DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS, - }), - }; + let card_testing_guard_config = self + .card_testing_guard_config + .map(CardTestingGuardConfig::foreign_from) + .or(Some(CardTestingGuardConfig::default())); Ok(domain::Profile::from(domain::ProfileSetter { id: profile_id, diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index b72b47be16d..4bd6dfbe5dc 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -16,7 +16,7 @@ pub use api_models::{ }, }; use common_utils::{ext_traits::ValueExt, types::keymanager as km_types}; -use diesel_models::organization::OrganizationBridge; +use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge}; use error_stack::ResultExt; use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; use masking::{ExposeInterface, PeekInterface, Secret}; @@ -141,6 +141,10 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { let masked_outgoing_webhook_custom_http_headers = outgoing_webhook_custom_http_headers.map(MaskedHeaders::from_headers); + let card_testing_guard_config = item + .card_testing_guard_config + .or(Some(CardTestingGuardConfig::default())); + Ok(Self { merchant_id: item.merchant_id, profile_id, @@ -186,9 +190,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { 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 - .map(ForeignInto::foreign_into), + card_testing_guard_config: card_testing_guard_config.map(ForeignInto::foreign_into), is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, force_3ds_challenge: item.force_3ds_challenge, is_debit_routing_enabled: Some(item.is_debit_routing_enabled), @@ -224,6 +226,10 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { let masked_outgoing_webhook_custom_http_headers = outgoing_webhook_custom_http_headers.map(MaskedHeaders::from_headers); + let card_testing_guard_config = item + .card_testing_guard_config + .or(Some(CardTestingGuardConfig::default())); + Ok(Self { merchant_id: item.merchant_id, id, @@ -264,9 +270,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { is_network_tokenization_enabled: item.is_network_tokenization_enabled, 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 - .map(ForeignInto::foreign_into), + card_testing_guard_config: card_testing_guard_config.map(ForeignInto::foreign_into), is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, is_debit_routing_enabled: Some(item.is_debit_routing_enabled), merchant_business_country: item.merchant_business_country, @@ -335,25 +339,10 @@ pub async fn create_profile_from_merchant_account( "fs", ))); - let card_testing_guard_config = match request.card_testing_guard_config { - Some(card_testing_guard_config) => Some(CardTestingGuardConfig::foreign_from( - card_testing_guard_config, - )), - None => Some(CardTestingGuardConfig { - is_card_ip_blocking_enabled: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_STATUS, - card_ip_blocking_threshold: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_THRESHOLD, - is_guest_user_card_blocking_enabled: - common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS, - guest_user_card_blocking_threshold: - common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD, - is_customer_id_blocking_enabled: - common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_STATUS, - customer_id_blocking_threshold: - common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD, - card_testing_guard_expiry: - common_utils::consts::DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS, - }), - }; + let card_testing_guard_config = request + .card_testing_guard_config + .map(CardTestingGuardConfig::foreign_from) + .or(Some(CardTestingGuardConfig::default())); Ok(domain::Profile::from(domain::ProfileSetter { profile_id,
2025-03-11T11:10:54Z
## 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 --> In our current implementation of `Card Testing Guard`, the `card_testing_guard_config` can be `NULL` for existing profiles. That has been fixed in this PR to return the default values for `card_testing_guard_config` in case the underlying data is `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). --> Issue Link: https://github.com/juspay/hyperswitch/issues/7598 ## 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 Tests** **Business Profile Retrieve** -Request ``` curl --location 'http://localhost:8080/account/postman_merchant_GHAction_28c1525e-4f97-4f53-82a2-7ea63214a26a/business_profile/pro_N8dPPL3N4soUk236Rbq2' \ --header 'api-key: test_admin' ``` -Response ``` { "merchant_id": "postman_merchant_GHAction_28c1525e-4f97-4f53-82a2-7ea63214a26a", "profile_id": "pro_N8dPPL3N4soUk236Rbq2", "profile_name": "US_default", "return_url": "https://duck.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "M59W9wzwjThfjmSUuTqagO3k9SaN74rA8BFa4NMGBTRCgzwl7Y9gBNgAAKl0FqHe", "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 }, "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 } ``` **Cypress Tests** ![image](https://github.com/user-attachments/assets/dc1560af-790c-4baf-8f57-1286c37a3431) ## 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.113.0
ae00ef9c081657d3da892c25432691870fb24bc9
ae00ef9c081657d3da892c25432691870fb24bc9
juspay/hyperswitch
juspay__hyperswitch-7600
Bug: [FEATURE] Single-Use PSP tokenization for making a payment ### Feature Description Have a single use PSP tokenisation feature which creates a token at PSP end for the payment methods service and return it to the user for using the same for using it to make payments ### Possible Implementation Add it to the confirm call of the payment method session call where we decided to create a Payment Method for the request given ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index a9de9611e56..9f641ddff62 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -19487,7 +19487,8 @@ "type": "object", "description": "The Payment Service Provider Configuration for payment methods that are created using the payment method session", "required": [ - "tokenization_type" + "tokenization_type", + "connector_id" ], "properties": { "tokenization_type": { @@ -19495,8 +19496,7 @@ }, "connector_id": { "type": "string", - "description": "The merchant connector id to be used for tokenization", - "nullable": true + "description": "The merchant connector id to be used for tokenization" } } }, diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 56bffc02640..1dfa9ce9d42 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -455,6 +455,15 @@ impl PaymentMethodCreate { _ => false, } } + pub fn get_tokenize_connector_id( + &self, + ) -> Result<id_type::MerchantConnectorAccountId, error_stack::Report<errors::ValidationError>> + { + self.psp_tokenization + .clone() + .get_required_value("psp_tokenization") + .map(|psp| psp.connector_id) + } } #[cfg(all( diff --git a/crates/common_types/src/payment_methods.rs b/crates/common_types/src/payment_methods.rs index 79cf34e1103..c6b492a1030 100644 --- a/crates/common_types/src/payment_methods.rs +++ b/crates/common_types/src/payment_methods.rs @@ -162,6 +162,6 @@ pub struct PspTokenization { pub tokenization_type: common_enums::TokenizationType, /// The merchant connector id to be used for tokenization - #[schema(value_type = Option<String>)] - pub connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, + #[schema(value_type = String)] + pub connector_id: common_utils::id_type::MerchantConnectorAccountId, } diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 1f99e5cbfb5..f69b9dc6855 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -6,6 +6,8 @@ use api_models::{ }, }; use common_enums::enums as api_enums; +#[cfg(feature = "v2")] +use common_utils::ext_traits::OptionExt; use common_utils::{ id_type, new_type::{ @@ -16,7 +18,6 @@ use common_utils::{ use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use time::Date; - // We need to derive Serialize and Deserialize because some parts of payment method data are being // stored in the database as serde_json::Value #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] @@ -688,6 +689,40 @@ pub enum MobilePaymentData { }, } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodData { + type Error = error_stack::Report<common_utils::errors::ValidationError>; + + fn try_from(value: payment_methods::PaymentMethodCreateData) -> Result<Self, Self::Error> { + match value { + payment_methods::PaymentMethodCreateData::Card(payment_methods::CardDetail { + card_number, + card_exp_month, + card_exp_year, + card_cvc, + card_issuer, + card_network, + card_type, + card_issuing_country, + nick_name, + card_holder_name, + }) => Ok(Self::Card(Card { + card_number, + card_exp_month, + card_exp_year, + card_cvc: card_cvc.get_required_value("card_cvc")?, + card_issuer, + card_network, + card_type: card_type.map(|card_type| card_type.to_string()), + card_issuing_country: card_issuing_country.map(|country| country.to_string()), + bank_code: None, + nick_name, + card_holder_name, + })), + } + } +} + impl From<api_models::payments::PaymentMethodData> for PaymentMethodData { fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self { match api_model_payment_method_data { @@ -1891,6 +1926,26 @@ impl From<NetworkTokenDetails> for NetworkTokenDetailsPaymentMethod { } } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct SingleUsePaymentMethodToken { + pub token: Secret<String>, + pub merchant_connector_id: id_type::MerchantConnectorAccountId, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl SingleUsePaymentMethodToken { + pub fn get_single_use_token_from_payment_method_token( + token: Secret<String>, + mca_id: id_type::MerchantConnectorAccountId, + ) -> Self { + Self { + token, + merchant_connector_id: mca_id, + } + } +} + impl From<NetworkTokenDetailsPaymentMethod> for payment_methods::NetworkTokenDetailsPaymentMethod { fn from(item: NetworkTokenDetailsPaymentMethod) -> Self { Self { @@ -1908,3 +1963,19 @@ impl From<NetworkTokenDetailsPaymentMethod> for payment_methods::NetworkTokenDet } } } + +#[cfg(feature = "v2")] +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub struct SingleUseTokenKey(String); + +#[cfg(feature = "v2")] +impl SingleUseTokenKey { + pub fn store_key(payment_method_id: &id_type::GlobalPaymentMethodId) -> Self { + let new_token = format!("single_use_token_{}", payment_method_id.get_string_repr()); + Self(new_token) + } + + pub fn get_store_key(&self) -> &str { + &self.0 + } +} diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index b6911f1f562..f06343ff9b4 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -464,6 +464,7 @@ pub struct MultibancoCreditTransferSourceRequest { #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripePaymentMethodData { + CardToken(StripeCardToken), Card(StripeCardData), PayLater(StripePayLaterData), Wallet(StripeWallet), @@ -472,6 +473,19 @@ pub enum StripePaymentMethodData { BankTransfer(StripeBankTransferData), } +// Struct to call the Stripe tokens API to create a PSP token for the card details provided +#[derive(Debug, Eq, PartialEq, Serialize)] +pub struct StripeCardToken { + #[serde(rename = "card[number]")] + pub token_card_number: cards::CardNumber, + #[serde(rename = "card[exp_month]")] + pub token_card_exp_month: Secret<String>, + #[serde(rename = "card[exp_year]")] + pub token_card_exp_year: Secret<String>, + #[serde(rename = "card[cvc]")] + pub token_card_cvc: Secret<String>, +} + #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(tag = "payment_method_data[type]")] pub enum BankDebitData { @@ -2094,15 +2108,30 @@ impl TryFrom<&types::SetupMandateRouterData> for SetupIntentRequest { impl TryFrom<&types::TokenizationRouterData> for TokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { - let payment_data = create_stripe_payment_method( - &item.request.payment_method_data, - item.auth_type, - item.payment_method_token.clone(), - None, - StripeBillingAddress::default(), - )?; + // Card flow for tokenization is handled seperately because of API contact difference + let request_payment_data = match &item.request.payment_method_data { + domain::PaymentMethodData::Card(card_details) => { + StripePaymentMethodData::CardToken(StripeCardToken { + token_card_number: card_details.card_number.clone(), + token_card_exp_month: card_details.card_exp_month.clone(), + token_card_exp_year: card_details.card_exp_year.clone(), + token_card_cvc: card_details.card_cvc.clone(), + }) + } + _ => { + create_stripe_payment_method( + &item.request.payment_method_data, + item.auth_type, + item.payment_method_token.clone(), + None, + StripeBillingAddress::default(), + )? + .0 + } + }; + Ok(Self { - token_data: payment_data.0, + token_data: request_payment_data, }) } } diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index e368a94b488..43041ef01b6 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -235,3 +235,12 @@ pub(crate) const SENDER_ID: &[u8] = b"Google"; /// Default value for the number of attempts to retry fetching forex rates pub const DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS: u64 = 3; + +/// Default payment intent id +pub const IRRELEVANT_PAYMENT_INTENT_ID: &str = "irrelevant_payment_intent_id"; + +/// Default payment attempt id +pub const IRRELEVANT_PAYMENT_ATTEMPT_ID: &str = "irrelevant_payment_attempt_id"; + +// Default payment method storing TTL in redis in seconds +pub const DEFAULT_PAYMENT_METHOD_STORE_TTL: i64 = 86400; // 1 day diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 27fb3959bfe..100b10012bc 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -15,7 +15,6 @@ pub mod transformers; pub mod utils; mod validator; pub mod vault; - use std::borrow::Cow; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use std::collections::HashSet; @@ -34,6 +33,7 @@ use common_utils::{consts::DEFAULT_LOCALE, id_type}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use common_utils::{ crypto::Encryptable, + errors::CustomResult, ext_traits::{AsyncExt, Encode, ValueExt}, fp_utils::when, generate_id, types as util_types, @@ -59,6 +59,8 @@ use masking::{PeekInterface, Secret}; use router_env::{instrument, tracing}; use time::Duration; +#[cfg(feature = "v2")] +use super::payments::tokenization; use super::{ errors::{RouterResponse, StorageErrorExt}, pm_auth, @@ -67,24 +69,28 @@ use super::{ use crate::{ configs::settings, core::{payment_methods::transformers as pm_transforms, payments as payments_core}, + db::errors::ConnectorErrorExt, headers, logger, routes::{self, payment_methods as pm_routes}, services::encryption, types::{ + self, api::{self, payment_methods::PaymentMethodCreateExt}, domain::types as domain_types, payment_methods as pm_types, storage::{ephemeral_key, PaymentMethodListContext}, transformers::{ForeignFrom, ForeignTryFrom}, + Tokenizable, }, utils::ext_traits::OptionExt, }; use crate::{ consts, core::{ - errors::{self, RouterResult}, + errors::{ProcessTrackerError, RouterResult}, payments::helpers as payment_helpers, }, + errors, routes::{app::StorageInterface, SessionState}, services, types::{ @@ -206,7 +212,7 @@ pub async fn initiate_pm_collect_link( ) .await?; - // Create DB entries + // Create DB entrie let pm_collect_link = create_pm_collect_db_entry( &state, &merchant_account, @@ -466,7 +472,7 @@ pub async fn add_payment_method_status_update_task( prev_status: enums::PaymentMethodStatus, curr_status: enums::PaymentMethodStatus, merchant_id: &id_type::MerchantId, -) -> Result<(), errors::ProcessTrackerError> { +) -> Result<(), ProcessTrackerError> { let created_at = payment_method.created_at; let schedule_time = created_at.saturating_add(Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)); @@ -988,7 +994,7 @@ pub async fn create_payment_method_core( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; - let resp = pm_transforms::generate_payment_method_response(&payment_method)?; + let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?; Ok((resp, payment_method)) } @@ -1033,7 +1039,7 @@ pub async fn network_tokenize_and_vault_the_pmd( network_tokenization_enabled_for_profile: bool, customer_id: &id_type::GlobalCustomerId, ) -> Option<NetworkTokenPaymentMethodDetails> { - let network_token_pm_details_result: errors::CustomResult< + let network_token_pm_details_result: CustomResult< NetworkTokenPaymentMethodDetails, errors::NetworkTokenizationError, > = async { @@ -1272,7 +1278,7 @@ pub async fn payment_method_intent_create( .await .attach_printable("Failed to add Payment method to DB")?; - let resp = pm_transforms::generate_payment_method_response(&payment_method)?; + let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?; Ok(services::ApplicationResponse::Json(resp)) } @@ -1523,7 +1529,7 @@ pub async fn create_payment_method_for_intent( payment_method_billing_address: Option< Encryptable<hyperswitch_domain_models::address::Address>, >, -) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { +) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { let db = &*state.store; let current_time = common_utils::date_time::now(); @@ -1758,7 +1764,7 @@ fn get_pm_list_context( } Some(payment_methods::PaymentMethodsData::BankDetails(bank_details)) => { let get_bank_account_token_data = - || -> errors::CustomResult<payment_methods::BankAccountTokenData, errors::ApiErrorResponse> { + || -> CustomResult<payment_methods::BankAccountTokenData,errors::ApiErrorResponse> { let connector_details = bank_details .connector_details .first() @@ -1885,7 +1891,14 @@ pub async fn retrieve_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; - transformers::generate_payment_method_response(&payment_method) + let single_use_token_in_cache = get_single_use_token_from_store( + &state.clone(), + payment_method_data::SingleUseTokenKey::store_key(&pm_id.clone()), + ) + .await + .unwrap_or_default(); + + transformers::generate_payment_method_response(&payment_method, &single_use_token_in_cache) .map(services::ApplicationResponse::Json) } @@ -2006,7 +2019,7 @@ pub async fn update_payment_method_core( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; - let response = pm_transforms::generate_payment_method_response(&payment_method)?; + let response = pm_transforms::generate_payment_method_response(&payment_method, &None)?; // Add a PT task to handle payment_method delete from vault @@ -2545,7 +2558,7 @@ pub async fn payment_methods_session_confirm( let payment_method = create_payment_method_core( &state, &req_state, - create_payment_method_request, + create_payment_method_request.clone(), &merchant_account, &key_store, &profile, @@ -2578,7 +2591,18 @@ pub async fn payment_methods_session_confirm( tokenization_type: common_enums::TokenizationType::SingleUse, .. }) => { - todo!("single use tokenization are not implemented") + Box::pin(create_single_use_tokenization_flow( + state.clone(), + req_state.clone(), + merchant_account.clone(), + profile.clone(), + key_store.clone(), + &create_payment_method_request.clone(), + &payment_method, + &payment_method_session, + )) + .await?; + None } None => None, }; @@ -2650,3 +2674,194 @@ impl pm_types::SavedPMLPaymentsInfo { Ok(()) } } + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[allow(clippy::too_many_arguments)] +async fn create_single_use_tokenization_flow( + state: SessionState, + req_state: routes::app::ReqState, + merchant_account: domain::MerchantAccount, + profile: domain::Profile, + key_store: domain::MerchantKeyStore, + payment_method_create_request: &payment_methods::PaymentMethodCreate, + payment_method: &api::PaymentMethodResponse, + payment_method_session: &domain::payment_methods::PaymentMethodSession, +) -> RouterResult<()> { + let customer_id = payment_method_create_request.customer_id.to_owned(); + let connector_id = payment_method_create_request + .get_tokenize_connector_id() + .change_context(errors::ApiErrorResponse::MissingRequiredField { + field_name: "psp_tokenization.connector_id", + }) + .attach_printable("Failed to get tokenize connector id")?; + + let db = &state.store; + + let merchant_connector_account_details = db + .find_merchant_connector_account_by_id(&(&state).into(), &connector_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: connector_id.get_string_repr().to_owned(), + }) + .attach_printable("error while fetching merchant_connector_account from connector_id")?; + let auth_type = merchant_connector_account_details + .get_connector_account_details() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while parsing value for ConnectorAuthType")?; + + let payment_method_data_request = types::PaymentMethodTokenizationData { + payment_method_data: payment_method_data::PaymentMethodData::try_from( + payment_method_create_request.payment_method_data.clone(), + ) + .change_context(errors::ApiErrorResponse::MissingRequiredField { + field_name: "card_cvc", + }) + .attach_printable( + "Failed to convert type from Payment Method Create Data to Payment Method Data", + )?, + browser_info: None, + currency: api_models::enums::Currency::default(), + amount: None, + }; + + let payment_method_session_address = types::PaymentAddress::new( + None, + payment_method_session + .billing + .clone() + .map(|address| address.into_inner()), + None, + None, + ); + + let mut router_data = + types::RouterData::<api::PaymentMethodToken, _, types::PaymentsResponseData> { + flow: std::marker::PhantomData, + merchant_id: merchant_account.get_id().clone(), + customer_id: None, + connector_customer: None, + connector: merchant_connector_account_details + .connector_name + .to_string(), + payment_id: consts::IRRELEVANT_PAYMENT_INTENT_ID.to_string(), //Static + attempt_id: consts::IRRELEVANT_PAYMENT_ATTEMPT_ID.to_string(), //Static + tenant_id: state.tenant.tenant_id.clone(), + status: common_enums::enums::AttemptStatus::default(), + payment_method: common_enums::enums::PaymentMethod::Card, + connector_auth_type: auth_type, + description: None, + address: payment_method_session_address, + auth_type: common_enums::enums::AuthenticationType::default(), + connector_meta_data: None, + connector_wallets_details: None, + amount_captured: None, + access_token: None, + session_token: None, + reference_id: None, + payment_method_token: None, + recurring_mandate_payment_data: None, + preprocessing_id: None, + payment_method_balance: None, + connector_api_version: None, + request: payment_method_data_request.clone(), + response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), + connector_request_reference_id: payment_method_session.id.get_string_repr().to_string(), + #[cfg(feature = "payouts")] + payout_method_data: None, + #[cfg(feature = "payouts")] + quote_id: None, + test_mode: None, + connector_http_status_code: None, + external_latency: None, + apple_pay_flow: None, + frm_metadata: None, + dispute_id: None, + refund_id: None, + connector_response: None, + payment_method_status: None, + minor_amount_captured: None, + integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, + connector_mandate_request_reference_id: None, + authentication_id: None, + psd2_sca_exemption_type: None, + }; + + let payment_method_token_response = tokenization::add_token_for_payment_method( + &mut router_data, + payment_method_data_request.clone(), + state.clone(), + &merchant_connector_account_details.clone(), + ) + .await?; + + let token_response = payment_method_token_response.token.map_err(|err| { + errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: (merchant_connector_account_details.clone()) + .connector_name + .to_string(), + status_code: err.status_code, + reason: err.reason, + } + })?; + + let value = payment_method_data::SingleUsePaymentMethodToken::get_single_use_token_from_payment_method_token( + token_response.clone().into(), + connector_id.clone() + ); + + let key = payment_method_data::SingleUseTokenKey::store_key(&payment_method.id); + + add_single_use_token_to_store(&state, key, value) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to store single use token")?; + + Ok(()) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +async fn add_single_use_token_to_store( + state: &SessionState, + key: payment_method_data::SingleUseTokenKey, + value: payment_method_data::SingleUsePaymentMethodToken, +) -> CustomResult<(), errors::StorageError> { + let redis_connection = state + .store + .get_redis_conn() + .map_err(Into::<errors::StorageError>::into)?; + + redis_connection + .serialize_and_set_key_with_expiry( + &payment_method_data::SingleUseTokenKey::get_store_key(&key).into(), + value, + consts::DEFAULT_PAYMENT_METHOD_STORE_TTL, + ) + .await + .change_context(errors::StorageError::KVError) + .attach_printable("Failed to insert payment method token to redis")?; + Ok(()) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +async fn get_single_use_token_from_store( + state: &SessionState, + key: payment_method_data::SingleUseTokenKey, +) -> CustomResult<Option<payment_method_data::SingleUsePaymentMethodToken>, errors::StorageError> { + let redis_connection = state + .store + .get_redis_conn() + .map_err(Into::<errors::StorageError>::into)?; + + redis_connection + .get_and_deserialize_key::<Option<payment_method_data::SingleUsePaymentMethodToken>>( + &payment_method_data::SingleUseTokenKey::get_store_key(&key).into(), + "SingleUsePaymentMethodToken", + ) + .await + .change_context(errors::StorageError::KVError) + .attach_printable("Failed to get payment method token from redis") +} diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index a7817329607..56a31732859 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -6,6 +6,8 @@ use common_utils::{ request::RequestContent, }; use error_stack::ResultExt; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use hyperswitch_domain_models::payment_method_data; use josekit::jwe; use router_env::tracing_actix_web::RequestId; use serde::{Deserialize, Serialize}; @@ -548,6 +550,7 @@ pub fn generate_pm_vaulting_req_from_update_request( #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn generate_payment_method_response( payment_method: &domain::PaymentMethod, + single_use_token: &Option<payment_method_data::SingleUsePaymentMethodToken>, ) -> errors::RouterResult<api::PaymentMethodResponse> { let pmd = payment_method .payment_method_data @@ -559,8 +562,7 @@ pub fn generate_payment_method_response( } _ => None, }); - - let connector_tokens = payment_method + let mut connector_tokens = payment_method .connector_mandate_details .as_ref() .and_then(|connector_token_details| connector_token_details.payments.clone()) @@ -570,7 +572,19 @@ pub fn generate_payment_method_response( .into_iter() .map(transformers::ForeignFrom::foreign_from) .collect::<Vec<_>>() - }); + }) + .unwrap_or_default(); + + if let Some(token) = single_use_token { + let connector_token_single_use = transformers::ForeignFrom::foreign_from(token); + connector_tokens.push(connector_token_single_use); + } + let connector_tokens = if connector_tokens.is_empty() { + None + } else { + Some(connector_tokens) + }; + let network_token_pmd = payment_method .network_token_payment_method_data .clone() @@ -1113,3 +1127,21 @@ impl } } } + +#[cfg(feature = "v2")] +impl transformers::ForeignFrom<&payment_method_data::SingleUsePaymentMethodToken> + for api_models::payment_methods::ConnectorTokenDetails +{ + fn foreign_from(token: &payment_method_data::SingleUsePaymentMethodToken) -> Self { + Self { + connector_id: token.clone().merchant_connector_id, + token_type: common_enums::TokenizationType::SingleUse, + status: api_enums::ConnectorTokenStatus::Active, + connector_token_request_reference_id: None, + original_payment_authorized_amount: None, + original_payment_authorized_currency: None, + metadata: None, + token: token.clone().token, + } + } +} diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 43d190edc74..1bc0152f4dd 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1343,3 +1343,68 @@ pub fn update_connector_mandate_details_status( payouts: None, })) } + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub async fn add_token_for_payment_method( + router_data: &mut types::RouterData< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + >, + payment_method_data_request: types::PaymentMethodTokenizationData, + state: SessionState, + merchant_connector_account_details: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, +) -> RouterResult<types::PspTokenResult> { + let connector_id = merchant_connector_account_details.id.clone(); + let connector_data = api::ConnectorData::get_connector_by_name( + &(state.conf.connectors), + &merchant_connector_account_details + .connector_name + .to_string(), + api::GetToken::Connector, + Some(connector_id.clone()), + )?; + + let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > = connector_data.connector.get_connector_integration(); + + let payment_method_token_response_data_type: Result< + types::PaymentsResponseData, + types::ErrorResponse, + > = Err(types::ErrorResponse::default()); + + let payment_method_token_router_data = + helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>( + router_data.clone(), + payment_method_data_request.clone(), + payment_method_token_response_data_type, + ); + + let connector_integration_response = services::execute_connector_processing_step( + &state, + connector_integration, + &payment_method_token_router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await + .to_payment_failed_response()?; + let payment_token_response = connector_integration_response.response.map(|res| { + if let types::PaymentsResponseData::TokenizationResponse { token } = res { + Ok(token) + } else { + Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get token from connector") + } + }); + + match payment_token_response { + Ok(token) => Ok(types::PspTokenResult { token: Ok(token?) }), + Err(error_response) => Ok(types::PspTokenResult { + token: Err(error_response), + }), + } +} diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index ff9eef080a6..1e1509f8dbc 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -513,6 +513,10 @@ pub struct PaymentMethodTokenResult { pub is_payment_method_tokenization_performed: bool, } +pub struct PspTokenResult { + pub token: Result<String, ErrorResponse>, +} + #[derive(Debug, Clone, Copy)] pub enum Redirection { Redirect,
2025-03-11T19:13:41Z
## 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 single use token implementation for Payment Method Service The feature would help to provide a single use PSP token for creating payment ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## 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 Payment Method Session Request ```bash curl --location 'http://localhost:8080/v2/payment-methods-session' \ --header 'x-profile-id: pro_2A1cEgnP0mOT4rqUqLtt' \ --header 'Authorization: api-key=dev_KVJIPqLBqYEGWUSse6Bggow5xL2PkaWLMYcpgTGcvr334sCVwagyUNbrBOTRnESf' \ --header 'Content-Type: application/json' \ --data-raw '{ "customer_id": "12345_cus_0195ab1d3f807a80bd6611b1b71cd1d0", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" },"psp_tokenization": { "tokenization_type": "single_use", "connector_id": "mca_lWefajNQ9HaKiJUhvAZo" } }' ``` Response ```json { "id": "12345_pms_0195ab1d677970a3bf12c0c019d42f6b", "customer_id": "12345_cus_0195ab1d3f807a80bd6611b1b71cd1d0", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "psp_tokenization": { "tokenization_type": "single_use", "connector_id": "mca_lWefajNQ9HaKiJUhvAZo" }, "network_tokenization": null, "expires_at": "2025-03-18T21:31:25.850Z", "client_secret": "cs_0195ab1d677a73c2a9b18b77354ad4ae", "return_url": null, "next_action": null, "authentication_details": null, "associated_payment_methods": null } ``` Confirm call for the Payment method session with `tokenization_type` as `single_use` under `psp_tokenization` in the request Request ```bash curl --location 'http://localhost:8080/v2/payment-methods-session/12345_pms_0195ab1d677970a3bf12c0c019d42f6b/confirm' \ --header 'x-profile-id: pro_2A1cEgnP0mOT4rqUqLtt' \ --header 'Authorization: publishable-key=pk_dev_427ac8f9e07d403a9dc21d71be6725cb,client-secret=cs_0195ab1d677a73c2a9b18b77354ad4ae' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_KVJIPqLBqYEGWUSse6Bggow5xL2PkaWLMYcpgTGcvr334sCVwagyUNbrBOTRnESf' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "04", "card_exp_year": "40", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "psp_tokenization": { "tokenization_type": "single_use", "connector_id": "mca_wmwOLCiB3NoMv8YwyxcE" } }' ``` Response ```json { "id": "12345_pms_0195ab1d677970a3bf12c0c019d42f6b", "customer_id": "12345_cus_0195ab1d3f807a80bd6611b1b71cd1d0", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "psp_tokenization": { "tokenization_type": "single_use", "connector_id": "mca_lWefajNQ9HaKiJUhvAZo" }, "network_tokenization": null, "expires_at": "2025-03-18T21:31:25.850Z", "client_secret": "CLIENT_SECRET_REDACTED", "return_url": null, "next_action": null, "authentication_details": null, "associated_payment_methods": null } ``` The way the same is stored in the Storage ( Redis ) ```bash 127.0.0.1:6379> get single_use_token_12345_pm_0195d26b9d2b71f094ba39e9fd131ca8 "{\"token\":\"tok_1R6t2xD5R7gDAGffQLz0D4fj\",\"merchant_connector_id\":\"mca_lWefajNQ9HaKiJUhvAZo\"}" ``` Retrieve API for the payment method created Request ```bash curl --location 'http://localhost:8080/v2/payment-methods/12345_pm_0195d26b9d2b71f094ba39e9fd131ca8' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_2A1cEgnP0mOT4rqUqLtt' \ --header 'api-key: dev_KVJIPqLBqYEGWUSse6Bggow5xL2PkaWLMYcpgTGcvr334sCVwagyUNbrBOTRnESf' \ --header 'Authorization: publishable-key=pk_dev_427ac8f9e07d403a9dc21d71be6725cb, api-key=dev_KVJIPqLBqYEGWUSse6Bggow5xL2PkaWLMYcpgTGcvr334sCVwagyUNbrBOTRnESf' ``` Response ```bash { "id": "12345_pm_0195d26b9d2b71f094ba39e9fd131ca8", "merchant_id": "apka_apna_test_gvHKZJ8EatRCipXedizy", "customer_id": "12345_cus_0195ab1d3f807a80bd6611b1b71cd1d0", "payment_method_type": "card", "payment_method_subtype": "credit", "recurring_enabled": false, "created": "2025-03-26T12:27:02.827Z", "last_used_at": "2025-03-26T12:27:02.827Z", "payment_method_data": { "card": { "issuer_country": null, "last4_digits": "4242", "expiry_month": "04", "expiry_year": "28", "card_holder_name": "John Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": null, "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "connector_tokens": [ { "connector_id": "mca_lWefajNQ9HaKiJUhvAZo", "token_type": "single_use", "status": "active", "connector_token_request_reference_id": null, "original_payment_authorized_amount": null, "original_payment_authorized_currency": null, "metadata": null, "token": "tok_1R6t2xD5R7gDAGffQLz0D4fj" } ], "network_token": null } ``` ## 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.113.0
617adfa33fd543131b5c4d8983319bfdcaa6c425
617adfa33fd543131b5c4d8983319bfdcaa6c425
juspay/hyperswitch
juspay__hyperswitch-7567
Bug: feat(router): Make `payment_method_subtype` optional We can have situations where we don't know the `payment_method_subtype`. e.g. Frontend doesn't know whether a `card` is `credit` or `debit`. To support such scenarios we need to make `payment_method_subtype` nullable
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index a2440cfccd3..c5ce0eec7d5 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -14738,7 +14738,6 @@ "type": "object", "required": [ "payment_method_type", - "payment_method_subtype", "customer_id", "payment_method_data" ], @@ -14747,7 +14746,12 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "$ref": "#/components/schemas/PaymentMethodType" + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodType" + } + ], + "nullable": true }, "metadata": { "type": "object", @@ -16199,8 +16203,7 @@ "description": "Request for Payment Intent Confirm", "required": [ "payment_method_data", - "payment_method_type", - "payment_method_subtype" + "payment_method_type" ], "properties": { "return_url": { @@ -16216,7 +16219,12 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "$ref": "#/components/schemas/PaymentMethodType" + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodType" + } + ], + "nullable": true }, "shipping": { "allOf": [ @@ -16994,8 +17002,7 @@ "amount_details", "customer_id", "payment_method_data", - "payment_method_type", - "payment_method_subtype" + "payment_method_type" ], "properties": { "amount_details": { @@ -17187,7 +17194,12 @@ "$ref": "#/components/schemas/PaymentMethod" }, "payment_method_subtype": { - "$ref": "#/components/schemas/PaymentMethodType" + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodType" + } + ], + "nullable": true }, "customer_acceptance": { "allOf": [ diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index d665337fda0..56bffc02640 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -116,8 +116,8 @@ pub struct PaymentMethodCreate { pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. - #[schema(value_type = PaymentMethodType,example = "credit")] - pub payment_method_subtype: api_enums::PaymentMethodType, + #[schema(value_type = Option<PaymentMethodType>,example = "credit")] + pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] @@ -2790,7 +2790,7 @@ pub struct PaymentMethodSessionConfirmRequest { /// The payment method subtype #[schema(value_type = PaymentMethodType, example = "credit")] - pub payment_method_subtype: common_enums::PaymentMethodType, + pub payment_method_subtype: Option<common_enums::PaymentMethodType>, /// The payment instrument data to be used for the payment #[schema(value_type = PaymentMethodDataRequest)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index b7d344317c7..87c765ce8fc 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5232,8 +5232,8 @@ pub struct PaymentsConfirmIntentRequest { pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided - #[schema(value_type = PaymentMethodType, example = "apple_pay")] - pub payment_method_subtype: api_enums::PaymentMethodType, + #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] + pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, @@ -5401,8 +5401,8 @@ pub struct PaymentsRequest { pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided - #[schema(value_type = PaymentMethodType, example = "apple_pay")] - pub payment_method_subtype: api_enums::PaymentMethodType, + #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] + pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] @@ -8477,7 +8477,7 @@ pub struct PaymentRevenueRecoveryMetadata { pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] - pub payment_method_subtype: common_enums::PaymentMethodType, + pub payment_method_subtype: Option<common_enums::PaymentMethodType>, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, @@ -8558,7 +8558,7 @@ pub struct PaymentsAttemptRecordRequest { /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] - pub payment_method_subtype: api_enums::PaymentMethodType, + pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 8fb4afeb8ed..672745bc39b 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -91,7 +91,7 @@ pub struct PaymentAttempt { pub charges: Option<common_types::payments::ConnectorChargeResponseData>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, - pub payment_method_subtype: storage_enums::PaymentMethodType, + pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, pub routing_result: Option<serde_json::Value>, pub authentication_applied: Option<common_enums::AuthenticationType>, pub external_reference_id: Option<String>, @@ -314,7 +314,7 @@ pub struct PaymentAttemptNew { pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, pub payment_method_type_v2: storage_enums::PaymentMethod, pub connector_payment_id: Option<ConnectorTransactionId>, - pub payment_method_subtype: storage_enums::PaymentMethodType, + pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, pub id: id_type::GlobalAttemptId, pub connector_token_details: Option<ConnectorTokenDetails>, pub card_discovery: Option<storage_enums::CardDiscovery>, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 5d028ad5214..30be42300c6 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -874,7 +874,7 @@ diesel::table! { #[max_length = 128] connector_payment_id -> Nullable<Varchar>, #[max_length = 64] - payment_method_subtype -> Varchar, + payment_method_subtype -> Nullable<Varchar>, routing_result -> Nullable<Jsonb>, authentication_applied -> Nullable<AuthenticationType>, #[max_length = 128] diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index eb2818ba244..69916de49a0 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -61,7 +61,7 @@ impl FeatureMetadata { pub fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> { self.payment_revenue_recovery_metadata .as_ref() - .map(|rrm| rrm.payment_method_subtype) + .and_then(|val| val.payment_method_subtype) } pub fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod> { @@ -158,7 +158,7 @@ pub struct PaymentRevenueRecoveryMetadata { ///Payment Method Type pub payment_method_type: common_enums::enums::PaymentMethod, /// PaymentMethod Subtype - pub payment_method_subtype: common_enums::enums::PaymentMethodType, + pub payment_method_subtype: Option<common_enums::enums::PaymentMethodType>, /// The name of the payment connector through which the payment attempt was made. pub connector: common_enums::connector_enums::Connector, } diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index e6e8e1b123f..557d2455279 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -447,8 +447,9 @@ impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptD let payment_method_details: ChargebeePaymentMethodDetails = serde_json::from_str(&item.content.transaction.payment_method_details) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - let payment_method_sub_type = - enums::PaymentMethodType::from(payment_method_details.card.funding_type); + let payment_method_sub_type = Some(enums::PaymentMethodType::from( + payment_method_details.card.funding_type, + )); Ok(Self { amount, currency, diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 9921cee8a63..d0a74406d50 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -226,7 +226,7 @@ impl AmountDetails { let order_tax_amount = match self.skip_external_tax_calculation { common_enums::TaxCalculationOverride::Skip => { self.tax_details.as_ref().and_then(|tax_details| { - tax_details.get_tax_amount(Some(confirm_intent_request.payment_method_subtype)) + tax_details.get_tax_amount(confirm_intent_request.payment_method_subtype) }) } common_enums::TaxCalculationOverride::Calculate => None, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 2dc4eec15f1..e6583db20e1 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -425,7 +425,7 @@ pub struct PaymentAttempt { /// The reference to the payment at the connector side pub connector_payment_id: Option<String>, /// The payment method subtype for the payment attempt. - pub payment_method_subtype: storage_enums::PaymentMethodType, + pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, /// The authentication type that was applied for the payment attempt. pub authentication_applied: Option<common_enums::AuthenticationType>, /// A reference to the payment at connector side. This is returned by the connector @@ -465,7 +465,7 @@ impl PaymentAttempt { #[cfg(feature = "v2")] pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethodType> { // TODO: check if we can fix this - Some(self.payment_method_subtype) + self.payment_method_subtype } #[cfg(feature = "v1")] @@ -649,8 +649,7 @@ impl PaymentAttempt { .unwrap_or(common_enums::PaymentMethod::Card), payment_method_id: None, connector_payment_id: None, - payment_method_subtype: payment_method_subtype_data - .unwrap_or(common_enums::PaymentMethodType::Credit), + payment_method_subtype: payment_method_subtype_data, authentication_applied: None, external_reference_id: None, payment_method_billing_address, diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs index 3e1bc93d91c..4bf1fece028 100644 --- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs @@ -31,7 +31,7 @@ pub struct RevenueRecoveryAttemptData { /// payment method of payment attempt. pub payment_method_type: common_enums::PaymentMethod, /// payment method sub type of the payment attempt. - pub payment_method_sub_type: common_enums::PaymentMethodType, + pub payment_method_sub_type: Option<common_enums::PaymentMethodType>, } /// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index eec47ca6255..27fb3959bfe 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -707,7 +707,7 @@ pub async fn retrieve_payment_method_with_token( pub(crate) fn get_payment_method_create_request( payment_method_data: &api_models::payments::PaymentMethodData, payment_method_type: storage_enums::PaymentMethod, - payment_method_subtype: storage_enums::PaymentMethodType, + payment_method_subtype: Option<storage_enums::PaymentMethodType>, customer_id: id_type::GlobalCustomerId, billing_address: Option<&api_models::payments::Address>, payment_method_session: Option<&domain::payment_methods::PaymentMethodSession>, @@ -971,7 +971,7 @@ pub async fn create_payment_method_core( None, network_tokenization_resp, Some(req.payment_method_type), - Some(req.payment_method_subtype), + req.payment_method_subtype, ) .await .attach_printable("Unable to create Payment method data")?; diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index ceac9eaf43a..e566b69534c 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -228,7 +228,7 @@ pub fn make_dsl_input( }; let payment_method_input = dsl_inputs::PaymentMethodInput { payment_method: Some(payments_dsl_input.payment_attempt.payment_method_type), - payment_method_type: Some(payments_dsl_input.payment_attempt.payment_method_subtype), + payment_method_type: payments_dsl_input.payment_attempt.payment_method_subtype, card_network: payments_dsl_input .payment_method_data .as_ref() diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5186bb32206..2da3e91caed 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -285,7 +285,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( session_token: None, enrolled_for_3ds: true, related_transaction_id: None, - payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), + payment_method_type: payment_data.payment_attempt.payment_method_subtype, router_return_url: Some(router_return_url), webhook_url, complete_authorize_url, @@ -607,7 +607,7 @@ pub async fn construct_router_data_for_psync<'a>( capture_method: Some(payment_intent.capture_method), connector_meta: attempt.connector_metadata.clone().expose_option(), sync_type: types::SyncRequestType::SinglePaymentSync, - payment_method_type: Some(attempt.payment_method_subtype), + payment_method_type: attempt.payment_method_subtype, currency: payment_intent.amount_details.currency, // TODO: Get the charges object from feature metadata split_payments: None, @@ -948,7 +948,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( email, customer_name: None, return_url: Some(router_return_url), - payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), + payment_method_type: payment_data.payment_attempt.payment_method_subtype, request_incremental_authorization: matches!( payment_data .payment_intent @@ -1666,7 +1666,7 @@ where created: payment_intent.created_at, payment_method_data, payment_method_type: Some(payment_attempt.payment_method_type), - payment_method_subtype: Some(payment_attempt.payment_method_subtype), + payment_method_subtype: payment_attempt.payment_method_subtype, next_action, connector_transaction_id: payment_attempt.connector_payment_id.clone(), connector_reference_id: None, @@ -1770,7 +1770,7 @@ where payment_method_subtype: self .payment_attempt .as_ref() - .map(|attempt| attempt.payment_method_subtype), + .and_then(|attempt| attempt.payment_method_subtype), connector_transaction_id: self .payment_attempt .as_ref() @@ -2897,7 +2897,7 @@ impl ForeignFrom<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> )), created: pi.created_at, payment_method_type: pa.as_ref().and_then(|p| p.payment_method_type.into()), - payment_method_subtype: pa.as_ref().and_then(|p| p.payment_method_subtype.into()), + payment_method_subtype: pa.as_ref().and_then(|p| p.payment_method_subtype), connector: pa.as_ref().and_then(|p| p.connector.clone()), merchant_connector_id: pa.as_ref().and_then(|p| p.merchant_connector_id.clone()), customer: None, diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 9c5030a30a0..4c925b9d467 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -69,10 +69,15 @@ impl PaymentMethodCreateExt for PaymentMethodCreate { impl PaymentMethodCreateExt for PaymentMethodCreate { fn validate(&self) -> RouterResult<()> { utils::when( - !validate_payment_method_type_against_payment_method( - self.payment_method_type, - self.payment_method_subtype, - ), + !self + .payment_method_subtype + .map(|sub| { + validate_payment_method_type_against_payment_method( + self.payment_method_type, + sub, + ) + }) + .unwrap_or(true), // If payment_method_subtype is None, we assume it to be valid || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid 'payment_method_type' provided".to_string() diff --git a/v2_migrations/2025-03-19-080705_payment-method-subtype-optional/down.sql b/v2_migrations/2025-03-19-080705_payment-method-subtype-optional/down.sql new file mode 100644 index 00000000000..d8983958168 --- /dev/null +++ b/v2_migrations/2025-03-19-080705_payment-method-subtype-optional/down.sql @@ -0,0 +1 @@ +ALTER TABLE payment_attempt ALTER COLUMN payment_method_subtype SET NOT NULL; diff --git a/v2_migrations/2025-03-19-080705_payment-method-subtype-optional/up.sql b/v2_migrations/2025-03-19-080705_payment-method-subtype-optional/up.sql new file mode 100644 index 00000000000..8f878c4e39f --- /dev/null +++ b/v2_migrations/2025-03-19-080705_payment-method-subtype-optional/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_attempt ALTER COLUMN payment_method_subtype DROP NOT NULL; \ No newline at end of file
2025-03-19T09:58:14Z
## 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 --> - Added diesel migration to make `payment_method_subtype` Nullable in `payment_attempt` table - Made `payment_method_subtype` an `Option` in request and response structs ### Additional Changes - [x] 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 #7567 ## 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. Payments - Confirm: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0195adf1544079139067663acdbff178/confirm-intent' \ --header 'x-client-secret: 12345_pay_0195adf1544079139067663acdbff178_secret_0195adf154487933ae61c8ca769286b0' \ --header 'x-profile-id: pro_6XA4kopfg4VAYLy2jNzW' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_196e797040ba4ecbb064ee14e53c8817' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card" }' ``` Response: ```json { "id": "12345_pay_0195adf1544079139067663acdbff178", "status": "requires_capture", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 100, "amount_captured": 0 }, "customer_id": null, "connector": "stripe", "client_secret": "12345_pay_0195adf1544079139067663acdbff178_secret_0195adf154487933ae61c8ca769286b0", "created": "2025-03-19T10:27:09.001Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": null, "connector_transaction_id": "pi_3R4Jq8D5R7gDAGff1B5K8RjQ", "connector_reference_id": null, "merchant_connector_id": "mca_vwmIHkB372B5SHcDO0wC", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": { "token": "pm_1R4Jq8D5R7gDAGffQmkzcinv", "connector_token_request_reference_id": "q0miVgxYfHkoOfwax6" }, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds" } ``` ## 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.113.0
a1ecce8f256081da1127f0ca4ed06356856c0e8b
a1ecce8f256081da1127f0ca4ed06356856c0e8b
juspay/hyperswitch
juspay__hyperswitch-7565
Bug: [BUG] AuthorizeDotNet Deserialization Failed in RSync Response in Production ### Bug Description AuthorizeDotNet has started sending status `voided` in RSync Response which is not mapped in Hyperswitch. ### Expected Behavior `voided` status should be mapped to `Failure`. ### Actual Behavior Deserialization failed. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: MacOS 2. Rust version (output of `rustc --version`): `rustc 1.83.0 (90b35a623 2024-11-26)` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index 2d329ec82fd..deefa7a1595 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -1562,6 +1562,7 @@ pub enum RSyncStatus { RefundPendingSettlement, Declined, GeneralError, + Voided, } #[derive(Debug, Deserialize, Serialize)] @@ -1615,7 +1616,9 @@ impl From<RSyncStatus> for enums::RefundStatus { match transaction_status { RSyncStatus::RefundSettledSuccessfully => Self::Success, RSyncStatus::RefundPendingSettlement => Self::Pending, - RSyncStatus::Declined | RSyncStatus::GeneralError => Self::Failure, + RSyncStatus::Declined | RSyncStatus::GeneralError | RSyncStatus::Voided => { + Self::Failure + } } } }
2025-03-19T08:34:21Z
## 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/7565) ## Description <!-- Describe your changes in detail --> Mapped status `voided` coming from AuthorizeDotNet to `Failure` in Hyperswitch. ### 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). --> AuthorizeDotNet has started sending status voided in RSync Response which is not mapped in Hyperswitch. As a result, deserialization failed. ## 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)? --> Can't be tested as AuthorizeDotNet takes 5-6 business days to send any other status than `RefundPendingSettlement`. ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] 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.113.0
10371af561ecc7536bb1db191af90a3cac2ab515
10371af561ecc7536bb1db191af90a3cac2ab515
juspay/hyperswitch
juspay__hyperswitch-7587
Bug: [CHORE] Update GlobalPay production endpoint at present, production endpoint points to sandbox and we need to point to production url
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 0ae089c5ea0..0d10ad5cbd9 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -8365,10 +8365,12 @@ "CAD", "CDF", "CHF", + "CLF", "CLP", "CNY", "COP", "CRC", + "CUC", "CUP", "CVE", "CZK", @@ -8464,6 +8466,7 @@ "SOS", "SRD", "SSP", + "STD", "STN", "SVC", "SYP", @@ -9969,6 +9972,12 @@ } } }, + { + "type": "string", + "enum": [ + "user_social_security_number" + ] + }, { "type": "string", "enum": [ diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index fa4ce7ae5eb..c4c18f6738f 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -10493,10 +10493,12 @@ "CAD", "CDF", "CHF", + "CLF", "CLP", "CNY", "COP", "CRC", + "CUC", "CUP", "CVE", "CZK", @@ -10592,6 +10594,7 @@ "SOS", "SRD", "SSP", + "STD", "STN", "SVC", "SYP", @@ -12170,6 +12173,12 @@ } } }, + { + "type": "string", + "enum": [ + "user_social_security_number" + ] + }, { "type": "string", "enum": [ diff --git a/config/deployments/production.toml b/config/deployments/production.toml index e193253e5ac..aaaa1b1216f 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -64,7 +64,7 @@ fiuu.secondary_base_url="https://api.merchant.razer.com/" fiuu.third_base_url="https://api.merchant.razer.com/" forte.base_url = "https://sandbox.forte.net/api/v3" getnet.base_url = "https://api.getneteurope.com/engine/rest" -globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/" +globalpay.base_url = "https://apis.globalpay.com/ucp/" globepay.base_url = "https://pay.globepay.co/" gocardless.base_url = "https://api.gocardless.com" gpayments.base_url = "https://{{merchant_endpoint_prefix}}-test.api.as1.gpayments.net" diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay.rs b/crates/hyperswitch_connectors/src/connectors/globalpay.rs index 641e9fd5f3d..8034f9ac9db 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay.rs @@ -482,8 +482,10 @@ impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Gl .response .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -561,7 +563,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Glo ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: GlobalpayPaymentsResponse = res .response - .parse_struct("globalpay PaymentsResponse") + .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); @@ -581,6 +583,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Glo )) .change_context(errors::ConnectorError::ResponseHandlingFailed) } + fn get_multiple_capture_sync_method( &self, ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> { @@ -658,8 +661,10 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo .response .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -748,8 +753,10 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData .response .parse_struct("Globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -909,8 +916,10 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Globalpay .response .parse_struct("globalpay RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(),
2025-03-21T07:47:05Z
## 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 updates the production endpoint url environment value for GlobalPay while fixing minor inconsistencies ### 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). --> At present, the production endpoint URL points to sandbox endpoint URL which is not intended. Closes #7587 ## 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)? --> NA. ## 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.113.0
0efeaa890f7dbcfa9440229d66d1a4f6b0f8b664
0efeaa890f7dbcfa9440229d66d1a4f6b0f8b664
juspay/hyperswitch
juspay__hyperswitch-7560
Bug: Revert "refactor(core): filter default routing config response based on connector type" This will revert pr https://github.com/juspay/hyperswitch/pull/7199
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 6c138488248..1a595cc7339 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -1,6 +1,6 @@ pub mod helpers; pub mod transformers; -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing::DynamicRoutingAlgoAccessor; @@ -11,7 +11,6 @@ use api_models::{ use async_trait::async_trait; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use common_utils::ext_traits::AsyncExt; -use common_utils::id_type::MerchantConnectorAccountId; use diesel_models::routing_algorithm::RoutingAlgorithm; use error_stack::ResultExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] @@ -19,9 +18,7 @@ use external_services::grpc_client::dynamic_routing::{ contract_routing_client::ContractBasedDynamicRouting, success_rate_client::SuccessBasedDynamicRouting, }; -use hyperswitch_domain_models::{ - mandates, merchant_connector_account::MerchantConnectorAccount, payment_address, -}; +use hyperswitch_domain_models::{mandates, payment_address}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use router_env::logger; use rustc_hash::FxHashSet; @@ -979,66 +976,16 @@ pub async fn retrieve_default_routing_config( ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]); let db = state.store.as_ref(); - let key_manager_state = &(&state).into(); - let key_store = state - .store - .get_merchant_key_store_by_merchant_id( - key_manager_state, - merchant_account.get_id(), - &state.store.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - let id = profile_id .map(|profile_id| profile_id.get_string_repr().to_owned()) .unwrap_or_else(|| merchant_account.get_id().get_string_repr().to_string()); - let mut merchant_connector_details: HashMap< - MerchantConnectorAccountId, - MerchantConnectorAccount, - > = HashMap::new(); - state - .store - .find_merchant_connector_account_by_merchant_id_and_disabled_list( - key_manager_state, - merchant_account.get_id(), - false, - &key_store, - ) + helpers::get_merchant_default_config(db, &id, transaction_type) .await - .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { - message: format!( - "Unable to find merchant_connector_accounts associate with merchant_id: {}", - merchant_account.get_id().get_string_repr() - ), - })? - .iter() - .for_each(|mca| { - merchant_connector_details.insert(mca.get_id(), mca.clone()); - }); - - let connectors = helpers::get_merchant_default_config(db, &id, transaction_type) - .await? - .iter() - .filter(|connector| { - connector - .merchant_connector_id - .as_ref() - .is_some_and(|mca_id| { - merchant_connector_details.get(mca_id).is_some_and(|mca| { - (*transaction_type == common_enums::TransactionType::Payment - && mca.connector_type == common_enums::ConnectorType::PaymentProcessor) - || (*transaction_type == common_enums::TransactionType::Payout - && mca.connector_type - == common_enums::ConnectorType::PayoutProcessor) - }) - }) + .map(|conn_choice| { + metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]); + service_api::ApplicationResponse::Json(conn_choice) }) - .cloned() - .collect::<Vec<routing_types::RoutableConnectorChoice>>(); - metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]); - Ok(service_api::ApplicationResponse::Json(connectors)) } #[cfg(feature = "v2")]
2025-03-18T13:11:12Z
Reverts juspay/hyperswitch#7199 ## 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 --> We are reverting the filtering of response for payment and payout processors. So this works as follows: If Payment's route is hit all the PaymentProcessors will be listed like PayoutConnectors etc. ### 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 after creating JWT locally and adding 1 payment and 1 payout connector. Payment : ``` curl --location 'http://localhost:8080/routing/default/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' ``` Payout : ``` curl --location 'http://localhost:8080/routing/payout/default/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWMyMTJhODgtOGFmYy00YjJjLWIwYWQtODY3MmQ2NTI3MzdlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQxMDAzMjgwIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTE3NjE1Miwib3JnX2lkIjoib3JnX1c4MkFMNTZ6VVE1dXFHcEEyYzFkIiwicHJvZmlsZV9pZCI6InByb19NcUlMcDAwdUFJeW5JZDdtUTNUTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.RoPyIG-JGrH6QmM6Gqd9gh03hOqy6MuC9Our9EHYGNk' ``` ## 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.113.0
e4c7ab8e683d969092910b3fcc046c2e65e18df9
e4c7ab8e683d969092910b3fcc046c2e65e18df9
juspay/hyperswitch
juspay__hyperswitch-7548
Bug: feat(analytics): add issuer as filter for authentication analytics hotfix Add acs_reference_number as filter for authentication analytics.
diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index bdcbdd86a94..4d11f19d531 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -169,6 +169,7 @@ pub async fn get_filters( AuthEventDimensions::ErrorMessage => fil.error_message, AuthEventDimensions::AuthenticationConnector => fil.authentication_connector.map(|i| i.as_ref().to_string()), AuthEventDimensions::MessageVersion => fil.message_version, + AuthEventDimensions::AcsReferenceNumber => fil.acs_reference_number, }) .collect::<Vec<String>>(); res.query_data.push(AuthEventFilterValue { diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs index 5f65eeaa279..1961116b84c 100644 --- a/crates/analytics/src/auth_events/filters.rs +++ b/crates/analytics/src/auth_events/filters.rs @@ -59,4 +59,5 @@ pub struct AuthEventFilterRow { pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>>, pub message_version: Option<String>, + pub acs_reference_number: Option<String>, } diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index a3d0fe7b683..6315c1338ee 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -45,6 +45,7 @@ pub struct AuthEventMetricRow { pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<storage_enums::AuthenticationConnectors>>, pub message_version: Option<String>, + pub acs_reference_number: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub start_bucket: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index b82d1ef4c35..fbdc4b75b3e 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -110,6 +110,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs index 682e8a07f6b..b4c0a5c5957 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -100,6 +100,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs index 047511d477c..b064cb7ab30 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs @@ -119,6 +119,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs index 9342e9047e0..3a122fd42a9 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs @@ -111,6 +111,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 984350efe6b..37435123623 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -105,6 +105,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index 5a2a9400b20..0265fc7e457 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -115,6 +115,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 279844388f2..178dcba20bf 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -107,6 +107,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index 91e8cc54289..b78f84326de 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -112,6 +112,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index b08edb10113..d114e36f140 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -108,6 +108,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index 80417ac64bf..a56d5b660aa 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -112,6 +112,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/types.rs b/crates/analytics/src/auth_events/types.rs index ac7ee2462ee..863e50a0af2 100644 --- a/crates/analytics/src/auth_events/types.rs +++ b/crates/analytics/src/auth_events/types.rs @@ -53,6 +53,15 @@ where ) .attach_printable("Error adding message version filter")?; } + + if !self.acs_reference_number.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::AcsReferenceNumber, + &self.acs_reference_number, + ) + .attach_printable("Error adding acs reference number filter")?; + } Ok(()) } } diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 6a6237e6783..5a2f097bb0d 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -231,6 +231,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let acs_reference_number: Option<String> = + row.try_get("acs_reference_number").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -249,6 +254,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow error_message, authentication_connector, message_version, + acs_reference_number, count, start_bucket, end_bucket, @@ -288,6 +294,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let acs_reference_number: Option<String> = + row.try_get("acs_reference_number").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; Ok(Self { authentication_status, trans_status, @@ -295,6 +306,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow error_message, authentication_connector, message_version, + acs_reference_number, }) } } diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index a0ddead1363..0832788e261 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -51,6 +51,7 @@ pub fn get_auth_event_dimensions() -> Vec<NameDescription> { vec![ AuthEventDimensions::AuthenticationConnector, AuthEventDimensions::MessageVersion, + AuthEventDimensions::AcsReferenceNumber, ] .into_iter() .map(Into::into) diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 2360e564642..8a1c168aa2f 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -23,6 +23,8 @@ pub struct AuthEventFilters { pub authentication_connector: Vec<AuthenticationConnectors>, #[serde(default)] pub message_version: Vec<String>, + #[serde(default)] + pub acs_reference_number: Vec<String>, } #[derive( @@ -50,6 +52,7 @@ pub enum AuthEventDimensions { ErrorMessage, AuthenticationConnector, MessageVersion, + AcsReferenceNumber, } #[derive( @@ -135,6 +138,7 @@ pub struct AuthEventMetricsBucketIdentifier { pub error_message: Option<String>, pub authentication_connector: Option<AuthenticationConnectors>, pub message_version: Option<String>, + pub acs_reference_number: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] @@ -151,6 +155,7 @@ impl AuthEventMetricsBucketIdentifier { error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, + acs_reference_number: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { @@ -160,6 +165,7 @@ impl AuthEventMetricsBucketIdentifier { error_message, authentication_connector, message_version, + acs_reference_number, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } @@ -173,6 +179,7 @@ impl Hash for AuthEventMetricsBucketIdentifier { self.authentication_type.hash(state); self.authentication_connector.hash(state); self.message_version.hash(state); + self.acs_reference_number.hash(state); self.error_message.hash(state); self.time_bucket.hash(state); }
2025-03-18T11:22:16Z
## 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 --> Hotfix PR Original PR: [https://github.com/juspay/hyperswitch/pull/7535](https://github.com/juspay/hyperswitch/pull/7535) ### 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.113.0
8c85c9c000cc203393a6e88f9fea093b192f18d7
8c85c9c000cc203393a6e88f9fea093b192f18d7
juspay/hyperswitch
juspay__hyperswitch-7536
Bug: refactor(dynamic_routing): change insert operation to upsert for dynamic_routing_stats ## Description <!-- Describe your changes in detail --> So previously we were only inserting in dynamic_routing_stats table, after this change we will be doing an Upsert operation instead of directly performing an insert operation.
diff --git a/crates/diesel_models/src/dynamic_routing_stats.rs b/crates/diesel_models/src/dynamic_routing_stats.rs index 90cf4689080..f60db1e9fbf 100644 --- a/crates/diesel_models/src/dynamic_routing_stats.rs +++ b/crates/diesel_models/src/dynamic_routing_stats.rs @@ -1,4 +1,4 @@ -use diesel::{Insertable, Queryable, Selectable}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::schema::dynamic_routing_stats; @@ -23,8 +23,8 @@ pub struct DynamicRoutingStatsNew { pub global_success_based_connector: Option<String>, } -#[derive(Clone, Debug, Eq, PartialEq, Queryable, Selectable, Insertable)] -#[diesel(table_name = dynamic_routing_stats, primary_key(payment_id), check_for_backend(diesel::pg::Pg))] +#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)] +#[diesel(table_name = dynamic_routing_stats, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct DynamicRoutingStats { pub payment_id: common_utils::id_type::PaymentId, pub attempt_id: String, @@ -43,3 +43,21 @@ pub struct DynamicRoutingStats { pub payment_method_type: Option<common_enums::PaymentMethodType>, pub global_success_based_connector: Option<String>, } + +#[derive( + Clone, Debug, Eq, PartialEq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, +)] +#[diesel(table_name = dynamic_routing_stats)] +pub struct DynamicRoutingStatsUpdate { + pub amount: common_utils::types::MinorUnit, + pub success_based_routing_connector: String, + pub payment_connector: String, + pub currency: Option<common_enums::Currency>, + pub payment_method: Option<common_enums::PaymentMethod>, + pub capture_method: Option<common_enums::CaptureMethod>, + pub authentication_type: Option<common_enums::AuthenticationType>, + pub payment_status: common_enums::AttemptStatus, + pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, + pub payment_method_type: Option<common_enums::PaymentMethodType>, + pub global_success_based_connector: Option<String>, +} diff --git a/crates/diesel_models/src/query/dynamic_routing_stats.rs b/crates/diesel_models/src/query/dynamic_routing_stats.rs index f6771cd103d..bf4cd706a69 100644 --- a/crates/diesel_models/src/query/dynamic_routing_stats.rs +++ b/crates/diesel_models/src/query/dynamic_routing_stats.rs @@ -1,6 +1,13 @@ +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; +use error_stack::report; + use super::generics; use crate::{ - dynamic_routing_stats::{DynamicRoutingStats, DynamicRoutingStatsNew}, + dynamic_routing_stats::{ + DynamicRoutingStats, DynamicRoutingStatsNew, DynamicRoutingStatsUpdate, + }, + errors, + schema::dynamic_routing_stats::dsl, PgPooledConn, StorageResult, }; @@ -9,3 +16,46 @@ impl DynamicRoutingStatsNew { generics::generic_insert(conn, self).await } } + +impl DynamicRoutingStats { + pub async fn find_optional_by_attempt_id_merchant_id( + conn: &PgPooledConn, + attempt_id: String, + merchant_id: &common_utils::id_type::MerchantId, + ) -> StorageResult<Option<Self>> { + generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::attempt_id.eq(attempt_id.to_owned())), + ) + .await + } + + pub async fn update( + conn: &PgPooledConn, + attempt_id: String, + merchant_id: &common_utils::id_type::MerchantId, + dynamic_routing_stat: DynamicRoutingStatsUpdate, + ) -> StorageResult<Self> { + generics::generic_update_with_results::< + <Self as HasTable>::Table, + DynamicRoutingStatsUpdate, + _, + _, + >( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::attempt_id.eq(attempt_id.to_owned())), + dynamic_routing_stat, + ) + .await? + .first() + .cloned() + .ok_or_else(|| { + report!(errors::DatabaseError::NotFound) + .attach_printable("Error while updating dynamic_routing_stats entry") + }) + } +} diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 1d40039e2a3..e80ddbead4c 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -14,7 +14,7 @@ use common_utils::ext_traits::ValueExt; use common_utils::{ext_traits::Encode, id_type, types::keymanager::KeyManagerState}; use diesel_models::configs; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use diesel_models::dynamic_routing_stats::DynamicRoutingStatsNew; +use diesel_models::dynamic_routing_stats::{DynamicRoutingStatsNew, DynamicRoutingStatsUpdate}; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use diesel_models::routing_algorithm; use error_stack::ResultExt; @@ -821,28 +821,6 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( first_merchant_success_based_connector_label.to_string(), ); - let dynamic_routing_stats = DynamicRoutingStatsNew { - payment_id: payment_attempt.payment_id.to_owned(), - attempt_id: payment_attempt.attempt_id.clone(), - merchant_id: payment_attempt.merchant_id.to_owned(), - profile_id: payment_attempt.profile_id.to_owned(), - amount: payment_attempt.get_total_amount(), - success_based_routing_connector: first_merchant_success_based_connector_label - .to_string(), - payment_connector: payment_connector.to_string(), - payment_method_type: payment_attempt.payment_method_type, - currency: payment_attempt.currency, - payment_method: payment_attempt.payment_method, - capture_method: payment_attempt.capture_method, - authentication_type: payment_attempt.authentication_type, - payment_status: payment_attempt.status, - conclusive_classification: outcome, - created_at: common_utils::date_time::now(), - global_success_based_connector: Some( - first_global_success_based_connector.label.to_string(), - ), - }; - core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add( 1, router_env::metric_attributes!( @@ -915,12 +893,74 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( ); logger::debug!("successfully pushed success_based_routing metrics"); - state + let duplicate_stats = state .store - .insert_dynamic_routing_stat_entry(dynamic_routing_stats) + .find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( + payment_attempt.attempt_id.clone(), + &payment_attempt.merchant_id.to_owned(), + ) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to push dynamic routing stats to db")?; + .attach_printable("Failed to fetch dynamic_routing_stats entry")?; + + if duplicate_stats.is_some() { + let dynamic_routing_update = DynamicRoutingStatsUpdate { + amount: payment_attempt.get_total_amount(), + success_based_routing_connector: first_merchant_success_based_connector_label + .to_string(), + payment_connector: payment_connector.to_string(), + payment_method_type: payment_attempt.payment_method_type, + currency: payment_attempt.currency, + payment_method: payment_attempt.payment_method, + capture_method: payment_attempt.capture_method, + authentication_type: payment_attempt.authentication_type, + payment_status: payment_attempt.status, + conclusive_classification: outcome, + global_success_based_connector: Some( + first_global_success_based_connector.label.to_string(), + ), + }; + + state + .store + .update_dynamic_routing_stats( + payment_attempt.attempt_id.clone(), + &payment_attempt.merchant_id.to_owned(), + dynamic_routing_update, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to update dynamic routing stats to db")?; + } else { + let dynamic_routing_stats = DynamicRoutingStatsNew { + payment_id: payment_attempt.payment_id.to_owned(), + attempt_id: payment_attempt.attempt_id.clone(), + merchant_id: payment_attempt.merchant_id.to_owned(), + profile_id: payment_attempt.profile_id.to_owned(), + amount: payment_attempt.get_total_amount(), + success_based_routing_connector: first_merchant_success_based_connector_label + .to_string(), + payment_connector: payment_connector.to_string(), + payment_method_type: payment_attempt.payment_method_type, + currency: payment_attempt.currency, + payment_method: payment_attempt.payment_method, + capture_method: payment_attempt.capture_method, + authentication_type: payment_attempt.authentication_type, + payment_status: payment_attempt.status, + conclusive_classification: outcome, + created_at: common_utils::date_time::now(), + global_success_based_connector: Some( + first_global_success_based_connector.label.to_string(), + ), + }; + + state + .store + .insert_dynamic_routing_stat_entry(dynamic_routing_stats) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to push dynamic routing stats to db")?; + }; client .update_success_rate( diff --git a/crates/router/src/db/dynamic_routing_stats.rs b/crates/router/src/db/dynamic_routing_stats.rs index d22f4fdd40b..f78655db0b3 100644 --- a/crates/router/src/db/dynamic_routing_stats.rs +++ b/crates/router/src/db/dynamic_routing_stats.rs @@ -16,6 +16,19 @@ pub trait DynamicRoutingStatsInterface { &self, dynamic_routing_stat_new: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>; + + async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( + &self, + attempt_id: String, + merchant_id: &common_utils::id_type::MerchantId, + ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError>; + + async fn update_dynamic_routing_stats( + &self, + attempt_id: String, + merchant_id: &common_utils::id_type::MerchantId, + data: storage::DynamicRoutingStatsUpdate, + ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>; } #[async_trait::async_trait] @@ -31,6 +44,33 @@ impl DynamicRoutingStatsInterface for Store { .await .map_err(|error| report!(errors::StorageError::from(error))) } + + async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( + &self, + attempt_id: String, + merchant_id: &common_utils::id_type::MerchantId, + ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::DynamicRoutingStats::find_optional_by_attempt_id_merchant_id( + &conn, + attempt_id, + merchant_id, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + async fn update_dynamic_routing_stats( + &self, + attempt_id: String, + merchant_id: &common_utils::id_type::MerchantId, + data: storage::DynamicRoutingStatsUpdate, + ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::DynamicRoutingStats::update(&conn, attempt_id, merchant_id, data) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } } #[async_trait::async_trait] @@ -42,6 +82,23 @@ impl DynamicRoutingStatsInterface for MockDb { ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { Err(errors::StorageError::MockDbError)? } + + async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( + &self, + _attempt_id: String, + _merchant_id: &common_utils::id_type::MerchantId, + ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn update_dynamic_routing_stats( + &self, + _attempt_id: String, + _merchant_id: &common_utils::id_type::MerchantId, + _data: storage::DynamicRoutingStatsUpdate, + ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } } #[async_trait::async_trait] @@ -55,4 +112,25 @@ impl DynamicRoutingStatsInterface for KafkaStore { .insert_dynamic_routing_stat_entry(dynamic_routing_stat) .await } + + async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( + &self, + attempt_id: String, + merchant_id: &common_utils::id_type::MerchantId, + ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { + self.diesel_store + .find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(attempt_id, merchant_id) + .await + } + + async fn update_dynamic_routing_stats( + &self, + attempt_id: String, + merchant_id: &common_utils::id_type::MerchantId, + data: storage::DynamicRoutingStatsUpdate, + ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { + self.diesel_store + .update_dynamic_routing_stats(attempt_id, merchant_id, data) + .await + } } diff --git a/crates/router/src/types/storage/dynamic_routing_stats.rs b/crates/router/src/types/storage/dynamic_routing_stats.rs index ba692a25255..2b1bc3f4a45 100644 --- a/crates/router/src/types/storage/dynamic_routing_stats.rs +++ b/crates/router/src/types/storage/dynamic_routing_stats.rs @@ -1 +1,3 @@ -pub use diesel_models::dynamic_routing_stats::{DynamicRoutingStats, DynamicRoutingStatsNew}; +pub use diesel_models::dynamic_routing_stats::{ + DynamicRoutingStats, DynamicRoutingStatsNew, DynamicRoutingStatsUpdate, +};
2025-03-02T18:34: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 --> So previously we were only inserting in dynamic_routing_stats table, after this change we will be doing an Upsert operation instead of directly performing an insert operation. ### 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)? --> The same flow is required, the way we test dynamic routing: 1. enable SR for a merchant. 2. set volume of payments to 100 for dynamic routing 3. make two consecutive payments(insure they end up in terminal state). 4. check the table `dynami_routing stats` for entry of both of them. ![Screenshot 2025-03-17 at 5 08 53 PM](https://github.com/user-attachments/assets/4cda988d-117c-45e5-9b5b-4dd8ff730ae5) ## 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.113.0
66e507e017fa7416f33aeae5f1ee60fd65d1d8b0
66e507e017fa7416f33aeae5f1ee60fd65d1d8b0
juspay/hyperswitch
juspay__hyperswitch-7541
Bug: [BUG] Deserialization issue when `account_name` is not passed for globalpay during mca create Issue: - When `account_name` is not passed, which is a [required](https://developer.globalpay.com/api/transactions#/transactions_post_request__account_name) field, `5xx` is thrown: ``` {"error":{"type":"api","message":"Something went wrong","code":"HE_00"}} ├╴at crates/router/src/services/api.rs:800:14 │ ├─▶ {"error":{"type":"server_not_available","code":"HE_00","message":"Something went wrong"}} │ ╰╴at crates/router/src/core/errors/utils.rs:321:17 │ ├─▶ Parsing failed │ ╰╴at crates/hyperswitch_connectors/src/utils.rs:288:50 │ ├─▶ Failed to parse struct: hyperswitch_connectors::connectors::globalpay::transformers::GlobalPayMeta │ ├╴at /router/crates/common_utils/src/ext_traits.rs:227:14 │ ╰╴Unable to parse hyperswitch_connectors::connectors::globalpay::transformers::GlobalPayMeta from serde_json::Value: Object {"google_pay": Object {"merchant_info": Object {"merchant_name": String("Narayan Bhat")}, "allowed_payment_methods": Array [Object {"type": String("CARD"), "parameters": Object {"allowed_auth_methods": Array [String("PAN_ONLY"), String("CRYPTOGRAM_3DS")], "allowed_card_networks": Array [String("AMEX"), String("DISCOVER"), String("INTERAC"), String("JCB"), String("MASTERCARD"), String("VISA")]}, "tokenization_specification": Object {"type": String("PAYMENT_GATEWAY"), "parameters": Object {"gateway": String("example"), "gateway_merchant_id": String("22956")}}}]}} │ ╰─▶ missing field `account_name` ╰╴at /router/crates/common_utils/src/ext_traits.rs:227:14 ```
diff --git a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs index 57cf5d0f287..24cfa66ef39 100644 --- a/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs @@ -1,6 +1,7 @@ use common_utils::{ crypto::{self, GenerateDigest}, errors::ParsingError, + pii, request::Method, types::{AmountConvertor, MinorUnit, StringMinorUnit, StringMinorUnitForConnector}, }; @@ -35,9 +36,8 @@ use super::{ use crate::{ types::{PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ - construct_captures_response_hashmap, to_connector_meta_from_secret, CardData, - ForeignTryFrom, MultipleCaptureSyncResponse, PaymentsAuthorizeRequestData, RouterData as _, - WalletData, + self, construct_captures_response_hashmap, CardData, ForeignTryFrom, + MultipleCaptureSyncResponse, PaymentsAuthorizeRequestData, RouterData as _, WalletData, }, }; @@ -66,13 +66,23 @@ pub struct GlobalPayMeta { account_name: Secret<String>, } +impl TryFrom<&Option<pii::SecretSerdeValue>> for GlobalPayMeta { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { + let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "metadata", + })?; + Ok(metadata) + } +} + impl TryFrom<&GlobalPayRouterData<&PaymentsAuthorizeRouterData>> for GlobalpayPaymentsRequest { type Error = Error; fn try_from( item: &GlobalPayRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { - let metadata: GlobalPayMeta = - to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())?; + let metadata = GlobalPayMeta::try_from(&item.router_data.connector_meta_data)?; let account_name = metadata.account_name; let (initiator, stored_credential, brand_reference) = get_mandate_details(item.router_data)?; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 454a090b639..e928decfdd7 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1388,6 +1388,7 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { } api_enums::Connector::Globalpay => { globalpay::transformers::GlobalpayAuthType::try_from(self.auth_type)?; + globalpay::transformers::GlobalPayMeta::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Globepay => {
2025-03-17T17:28:25Z
## 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 address the 5xx that occurs with GlobalPay connector when the required field `account_name` is not passed during MCA creation. Below migration needs to be run on hosted environments: ```sql UPDATE merchant_connector_account SET metadata = jsonb_set( metadata, '{account_name}', '""', true ) WHERE connector_name = 'globalpay' AND NOT metadata ? 'account_name'; ``` ### 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). --> Getting the connector production ready. ## 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>0. try creating mca without passing `metadata` field</summary> ```curl curl --location 'http://Localhost:8080/account/postman_merchant_GHAction_b7e0e1f4-ca0a-495e-8a6f-915769911e30/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "globalpay", "connector_account_details": { "auth_type": "BodyKey", "api_key": "key", "key1": "key1" }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "installment_payment_enabled": true, "recurring_enabled": true } ] } ] }' ``` ```json { "error": { "type": "invalid_request", "message": "The metadata is invalid", "code": "IR_06" } } ``` </details> <details> <summary>1. try creating mca with `metadata` field but different values</summary> ```curl curl --location 'http://Localhost:8080/account/postman_merchant_GHAction_b7e0e1f4-ca0a-495e-8a6f-915769911e30/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "globalpay", "connector_account_details": { "auth_type": "BodyKey", "api_key": "key", "key1": "key1" }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "installment_payment_enabled": true, "recurring_enabled": true } ] } ] , "metadata": { "city": "NY", "unit": "245" } }' ``` ```json { "error": { "type": "invalid_request", "message": "The metadata is invalid", "code": "IR_06" } } ``` </details> <details> <summary>2. try creating mca with `metadata` field with valid values</summary> ```curl curl --location 'http://Localhost:8080/account/postman_merchant_GHAction_b7e0e1f4-ca0a-495e-8a6f-915769911e30/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "globalpay", "connector_account_details": { "auth_type": "BodyKey", "api_key": "key", "key1": "key11" }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "installment_payment_enabled": true, "recurring_enabled": true } ] } ], "metadata": { "account_name": "transaction_processing" } }' ``` ```json { "connector_type": "payment_processor", "connector_name": "globalpay", "connector_label": "globalpay_US_default", "merchant_connector_id": "mca_lZZrlORyN0n7fuQpEgKz", "profile_id": "pro_cKEsY4S7wK3izgeOFXhw", "connector_account_details": { "auth_type": "BodyKey", "api_key": "****************", "key1": "********************************" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": null, "metadata": { "account_name": "transaction_processing" }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null } ``` </details> <details> <summary>3. try creating mca with `metadata` field with valid values and additional values like certs</summary> ```curl curl --location 'http://Localhost:8080/account/postman_merchant_GHAction_798f9222-9a5f-4cb3-8e61-3ae4c576b6b9/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "globalpay", "connector_account_details": { "auth_type": "BodyKey", "api_key": "key", "key1": "key1" }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "installment_payment_enabled": true, "recurring_enabled": true } ] } ], "metadata": { "account_name": "transaction_processing" , "google_pay": { "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "example", "gateway_merchant_id": "22956" } } } ], "merchant_info": { "merchant_name": "Narayan Bhat" } } } }' ``` ```json { "connector_type": "payment_processor", "connector_name": "globalpay", "connector_label": "globalpay_US_default", "merchant_connector_id": "mca_a45nhudvFQkdJeOTrJqd", "profile_id": "pro_zdAl1MuX7MuMUsGzlRZw", "connector_account_details": { "auth_type": "BodyKey", "api_key": "****************", "key1": "********************************" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": null, "metadata": { "google_pay": { "merchant_info": { "merchant_name": "Narayan Bhat" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "example", "gateway_merchant_id": "22956" } } } ] }, "account_name": "transaction_processing" }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null } ``` </details> <details> <summary>4. tried making a payment</summary> ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_8jOdTW9kwO9a50lrA8OfxY6m0iDGOhjpi2BJseJtaCU9xFz5YR6ROHuKYCeiTuz7' \ --data-raw '{ "amount": 1000, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4263970000005262", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } } }' ``` ```json { "payment_id": "pay_APA4HDesgk5NntotYd5P", "merchant_id": "postman_merchant_GHAction_798f9222-9a5f-4cb3-8e61-3ae4c576b6b9", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "globalpay", "client_secret": "pay_APA4HDesgk5NntotYd5P_secret_VLhRFg5ApKxEhnzxQbho", "created": "2025-03-17T17:25:53.489Z", "currency": "EUR", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "5262", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "426397", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1742232353, "expires": 1742235953, "secret": "epk_84c190a7359d4428a18118725e659805" }, "manual_retry_allowed": false, "connector_transaction_id": "TRN_aQvML8KHNMNMhOv3OHBZhO3hK3xQXC_5NntotYd5P_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_APA4HDesgk5NntotYd5P_1", "payment_link": null, "profile_id": "pro_zdAl1MuX7MuMUsGzlRZw", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_a45nhudvFQkdJeOTrJqd", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-17T17:40:53.489Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-17T17:25:55.934Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` </details> ## 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.113.0
10371af561ecc7536bb1db191af90a3cac2ab515
10371af561ecc7536bb1db191af90a3cac2ab515
juspay/hyperswitch
juspay__hyperswitch-7543
Bug: add support for cost based debit routing For every payment that occurs, there are three fees associated with the network: 1. Network Fee Every network has its own network fee structure, which typically includes both a percentage (% of the amount) and a fixed fee. For each payment, the respective network will charge a specific percentage and a fixed amount. 2. Interchange Fee If the bank is a regulated bank, it can charge only a specified percentage and fixed amount for the transaction. If the bank is not a regulated bank, then, similar to the network fee, the bank can charge different amounts depending on the network. 3. Fraud Check Fee When a bank is regulated under an exemption for fraud checks, it may charge an additional fee only if a fraud check is conducted. When a payment is being performed all this factors should be taken in consideration and a network should be chosen according to merchant's configuration
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 76b65a1433e..b475142a570 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -7334,7 +7334,11 @@ "UnionPay", "Interac", "RuPay", - "Maestro" + "Maestro", + "Star", + "Pulse", + "Accel", + "Nyce" ] }, "CardNetworkTokenizeRequest": { diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index db90936370b..c71ee457f5d 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -9284,7 +9284,11 @@ "UnionPay", "Interac", "RuPay", - "Maestro" + "Maestro", + "Star", + "Pulse", + "Accel", + "Nyce" ] }, "CardNetworkTokenizeRequest": { diff --git a/config/config.example.toml b/config/config.example.toml index 4cfe6a61e38..9f34eea38fb 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -441,6 +441,12 @@ braintree = { long_lived_token = false, payment_method = "card" } gocardless = { long_lived_token = true, payment_method = "bank_debit" } billwerk = { long_lived_token = false, payment_method = "card" } +[debit_routing_config] # Debit Routing configs +supported_currencies = "USD" # Supported currencies for debit routing +supported_connectors = "adyen" # Supported connectors for debit routing + +[debit_routing_config.connector_supported_debit_networks] # Debit Routing config that contains the supported debit networks for each connector +adyen = "Star,Pulse,Accel,Nyce" # Debit networks supported by adyen connector [temp_locker_enable_config] stripe = { payment_method = "bank_transfer" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 79074230917..1a15867e7db 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -590,6 +590,13 @@ eps = { country = "AT", currency = "EUR" } ideal = { country = "NL", currency = "EUR" } przelewy24 = { country = "PL", currency = "PLN,EUR" } +[debit_routing_config] +supported_currencies = "USD" +supported_connectors = "adyen" + +[debit_routing_config.connector_supported_debit_networks] +adyen = "Star,Pulse,Accel,Nyce" + [pm_filters.rapyd] apple_pay = { country = "AL,AS,AD,AR,AM,AU,AT,AZ,BH,BE,BM,BA,BR,BG,CA,KH,KY,CL,CO,CR,HR,CY,CZ,DK,DO,EC,SV,EE,FO,FI,FR,GE,DE,GI,GR,GL,GU,GT,GG,HN,HK,HU,IS,IE,IM,IL,IT,JP,KZ,KG,KW,LV,LI,LT,LU,MO,MY,MT,MX,MD,MC,ME,MA,NL,NZ,NI,MK,MP,NO,PA,PY,PR,PE,PL,PT,QA,RO,SM,RS,SG,SK,SI,ZA,ES,SE,CH,TW,TJ,TH,UA,AE,GB,US,UY,VI,VN", currency = "EUR,GBP,ISK,USD" } google_pay = { country = "AM,AT,AU,AZ,BA,BE,BG,BY,CA,CH,CL,CN,CO,CR,CY,CZ,DE,DK,DO,EC,EE,EG,ES,FI,FR,GB,GE,GL,GR,GT,HK,HN,HR,HU,IE,IL,IM,IS,IT,JE,JP,JO,KZ,KW,LA,LI,LT,LU,LV,MA,MC,MD,ME,MO,MN,MT,MX,MY,NC,NL,NO,NZ,OM,PA,PE,PL,PR,PT,QA,RO,RS,SA,SE,SG,SI,SK,SM,SV,TH,TW,UA,US,UY,VA,VN,ZA", currency = "EUR,GBP,ISK,USD" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 43f764f4e02..da9ad3daa4a 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -172,6 +172,13 @@ base_url = "https://app.hyperswitch.io" force_two_factor_auth = false force_cookies = false +[debit_routing_config] +supported_currencies = "USD" +supported_connectors = "adyen" + +[debit_routing_config.connector_supported_debit_networks] +adyen = "Star,Pulse,Accel,Nyce" + [frm] enabled = true diff --git a/config/development.toml b/config/development.toml index ccf5649951d..aeee9151c37 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1045,6 +1045,13 @@ payout_analytics_topic = "hyperswitch-payout-events" consolidated_events_topic = "hyperswitch-consolidated-events" authentication_analytics_topic = "hyperswitch-authentication-events" +[debit_routing_config] +supported_currencies = "USD" +supported_connectors = "adyen" + +[debit_routing_config.connector_supported_debit_networks] +adyen = "Star,Pulse,Accel,Nyce" + [analytics] source = "sqlx" forex_enabled = false diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 9ac4bb7f352..a82ba8c4a0e 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -594,6 +594,12 @@ eps = { country = "DE",currency = "EUR" } apple_pay = { country = "DE",currency = "EUR" } paypal = { country = "DE",currency = "EUR" } +[debit_routing_config] +supported_currencies = "USD" +supported_connectors = "adyen" + +[debit_routing_config.connector_supported_debit_networks] +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" } diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index 1d5bfd58467..87e874f7fa5 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -23,7 +23,6 @@ pub mod gsm; pub mod health_check; pub mod locker_migration; pub mod mandates; -#[cfg(feature = "dynamic_routing")] pub mod open_router; pub mod organization; pub mod payment_methods; diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index 07af605892f..f80623efc64 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -1,6 +1,6 @@ use std::{collections::HashMap, fmt::Debug}; -use common_utils::{id_type, types::MinorUnit}; +use common_utils::{errors, id_type, types::MinorUnit}; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ @@ -10,7 +10,10 @@ pub use euclid::{ }; use serde::{Deserialize, Serialize}; -use crate::enums::{Currency, PaymentMethod}; +use crate::{ + enums::{Currency, PaymentMethod}, + payment_methods, +}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -27,6 +30,7 @@ pub struct OpenRouterDecideGatewayRequest { pub enum RankingAlgorithm { SrBasedRouting, PlBasedRouting, + NtwBasedRouting, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -38,7 +42,7 @@ pub struct PaymentInfo { // customerId: Option<ETCu::CustomerId>, // preferredGateway: Option<ETG::Gateway>, pub payment_type: String, - // metadata: Option<String>, + pub metadata: Option<String>, // internalMetadata: Option<String>, // isEmi: Option<bool>, // emiBank: Option<String>, @@ -48,7 +52,7 @@ pub struct PaymentInfo { // paymentSource: Option<String>, // authType: Option<ETCa::txn_card_info::AuthType>, // cardIssuerBankName: Option<String>, - // cardIsin: Option<String>, + pub card_isin: Option<String>, // cardType: Option<ETCa::card_type::CardType>, // cardSwitchProvider: Option<Secret<String>>, } @@ -56,6 +60,63 @@ pub struct PaymentInfo { #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct DecidedGateway { pub gateway_priority_map: Option<HashMap<String, f64>>, + pub debit_routing_output: Option<DebitRoutingOutput>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct DebitRoutingOutput { + pub co_badged_card_networks: Vec<common_enums::CardNetwork>, + pub issuer_country: common_enums::CountryAlpha2, + pub is_regulated: bool, + pub regulated_name: Option<common_enums::RegulatedName>, + pub card_type: common_enums::CardType, +} + +impl From<&DebitRoutingOutput> for payment_methods::CoBadgedCardData { + fn from(output: &DebitRoutingOutput) -> Self { + Self { + co_badged_card_networks: output.co_badged_card_networks.clone(), + issuer_country_code: output.issuer_country, + is_regulated: output.is_regulated, + regulated_name: output.regulated_name.clone(), + } + } +} + +impl TryFrom<(payment_methods::CoBadgedCardData, String)> for DebitRoutingRequestData { + type Error = error_stack::Report<errors::ParsingError>; + + fn try_from( + (output, card_type): (payment_methods::CoBadgedCardData, String), + ) -> Result<Self, Self::Error> { + let parsed_card_type = card_type.parse::<common_enums::CardType>().map_err(|_| { + error_stack::Report::new(errors::ParsingError::EnumParseFailure("CardType")) + })?; + + Ok(Self { + co_badged_card_networks: output.co_badged_card_networks, + issuer_country: output.issuer_country_code, + is_regulated: output.is_regulated, + regulated_name: output.regulated_name, + card_type: parsed_card_type, + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CoBadgedCardRequest { + pub merchant_category_code: common_enums::MerchantCategoryCode, + pub acquirer_country: common_enums::CountryAlpha2, + pub co_badged_card_data: Option<DebitRoutingRequestData>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct DebitRoutingRequestData { + pub co_badged_card_networks: Vec<common_enums::CardNetwork>, + pub issuer_country: common_enums::CountryAlpha2, + pub is_regulated: bool, + pub regulated_name: Option<common_enums::RegulatedName>, + pub card_type: common_enums::CardType, } #[derive(Debug, Serialize, Deserialize)] diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index df4074dc00c..6e9a174c9f6 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -985,6 +985,15 @@ pub struct CardDetailsPaymentMethod { pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, + pub co_badged_card_data: Option<CoBadgedCardData>, +} + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct CoBadgedCardData { + pub co_badged_card_networks: Vec<api_enums::CardNetwork>, + pub issuer_country_code: common_enums::CountryAlpha2, + pub is_regulated: bool, + pub regulated_name: Option<common_enums::RegulatedName>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] @@ -1313,6 +1322,7 @@ impl From<CardDetail> for CardDetailsPaymentMethod { card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, + co_badged_card_data: None, } } } @@ -1321,8 +1331,10 @@ impl From<CardDetail> for CardDetailsPaymentMethod { any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] -impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { - fn from(item: CardDetailFromLocker) -> Self { +impl From<(CardDetailFromLocker, Option<&CoBadgedCardData>)> for CardDetailsPaymentMethod { + fn from( + (item, co_badged_card_data): (CardDetailFromLocker, Option<&CoBadgedCardData>), + ) -> Self { Self { issuer_country: item.issuer_country, last4_digits: item.last4_digits, @@ -1335,6 +1347,7 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, + co_badged_card_data: co_badged_card_data.cloned(), } } } @@ -1354,6 +1367,7 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, + co_badged_card_data: None, } } } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 880062cef21..226471dcc74 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2310,6 +2310,130 @@ pub enum CardNetwork { RuPay, #[serde(alias = "MAESTRO")] Maestro, + #[serde(alias = "STAR")] + Star, + #[serde(alias = "PULSE")] + Pulse, + #[serde(alias = "ACCEL")] + Accel, + #[serde(alias = "NYCE")] + Nyce, +} + +#[derive( + Clone, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumIter, + strum::EnumString, + utoipa::ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +pub enum RegulatedName { + #[serde(rename = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")] + #[strum(serialize = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")] + NonExemptWithFraud, + + #[serde(untagged)] + #[strum(default)] + Unknown(String), +} + +#[derive( + Clone, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumIter, + strum::EnumString, + utoipa::ToSchema, + Copy, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "lowercase")] +pub enum PanOrToken { + Pan, + Token, +} + +#[derive( + Clone, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumIter, + strum::EnumString, + utoipa::ToSchema, + Copy, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[strum(serialize_all = "UPPERCASE")] +#[serde(rename_all = "snake_case")] +pub enum CardType { + Credit, + Debit, +} + +#[derive(Debug, Clone, Serialize, Deserialize, strum::EnumString, strum::Display)] +#[serde(rename_all = "snake_case")] +pub enum MerchantCategoryCode { + #[serde(rename = "merchant_category_code_0001")] + Mcc0001, +} + +impl CardNetwork { + pub fn is_global_network(&self) -> bool { + match self { + Self::Interac + | Self::Star + | Self::Pulse + | Self::Accel + | Self::Nyce + | Self::CartesBancaires => false, + + Self::Visa + | Self::Mastercard + | Self::AmericanExpress + | Self::JCB + | Self::DinersClub + | Self::Discover + | Self::UnionPay + | Self::RuPay + | Self::Maestro => true, + } + } + + pub fn is_us_local_network(&self) -> bool { + match self { + Self::Star | Self::Pulse | Self::Accel | Self::Nyce => true, + Self::Interac + | Self::CartesBancaires + | Self::Visa + | Self::Mastercard + | Self::AmericanExpress + | Self::JCB + | Self::DinersClub + | Self::Discover + | Self::UnionPay + | Self::RuPay + | Self::Maestro => false, + } + } } /// Stage of the dispute diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 55dcc4e5bd2..40b37b6b3c5 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -402,6 +402,11 @@ impl MinorUnit { Self(value) } + /// checks if the amount is greater than the given value + pub fn is_greater_than(&self, value: i64) -> bool { + self.get_amount_as_i64() > value + } + /// Convert the amount to its major denomination based on Currency and return String /// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies. /// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/ diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index a4403923fd5..b46733d17cf 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -83,6 +83,14 @@ merchant_secret="Source verification key" payment_method_type = "Mastercard" [[adyen.debit]] payment_method_type = "Visa" +[[adyen.debit]] + payment_method_type = "Nyce" +[[adyen.debit]] + payment_method_type = "Pulse" +[[adyen.debit]] + payment_method_type = "Star" +[[adyen.debit]] + payment_method_type = "Accel" [[adyen.debit]] payment_method_type = "Interac" [[adyen.debit]] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index d9dea35440b..331c92c39ba 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -83,6 +83,14 @@ merchant_secret="Source verification key" payment_method_type = "Mastercard" [[adyen.debit]] payment_method_type = "Visa" +[[adyen.debit]] + payment_method_type = "Nyce" +[[adyen.debit]] + payment_method_type = "Pulse" +[[adyen.debit]] + payment_method_type = "Star" +[[adyen.debit]] + payment_method_type = "Accel" [[adyen.debit]] payment_method_type = "Interac" [[adyen.debit]] diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index c899c62561f..26ba1cbe52b 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -1257,6 +1257,7 @@ pub enum CardBrand { Visa, MC, Amex, + Accel, Argencard, Bcmc, Bijcard, @@ -1281,13 +1282,16 @@ pub enum CardBrand { Mir, Naranja, Oasis, + Pulse, Rupay, Shopping, + Star, Solo, Troy, Uatp, Visaalphabankbonus, Visadankort, + Nyce, Warehouse, } @@ -2091,6 +2095,10 @@ fn get_adyen_card_network(card_network: common_enums::CardNetwork) -> Option<Car common_enums::CardNetwork::UnionPay => Some(CardBrand::Cup), common_enums::CardNetwork::RuPay => Some(CardBrand::Rupay), common_enums::CardNetwork::Maestro => Some(CardBrand::Maestro), + common_enums::CardNetwork::Star => Some(CardBrand::Star), + common_enums::CardNetwork::Accel => Some(CardBrand::Accel), + common_enums::CardNetwork::Pulse => Some(CardBrand::Pulse), + common_enums::CardNetwork::Nyce => Some(CardBrand::Nyce), common_enums::CardNetwork::Interac => None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs index 3a627fdfdf8..7aed189fbd7 100644 --- a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs @@ -556,7 +556,12 @@ fn get_boa_card_type(card_network: common_enums::CardNetwork) -> Option<&'static common_enums::CardNetwork::UnionPay => Some("062"), //"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024" common_enums::CardNetwork::Maestro => Some("042"), - common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay => None, + common_enums::CardNetwork::Interac + | common_enums::CardNetwork::RuPay + | common_enums::CardNetwork::Star + | common_enums::CardNetwork::Accel + | common_enums::CardNetwork::Pulse + | common_enums::CardNetwork::Nyce => None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index 85125d1ddcc..25eedcd5e65 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -4305,7 +4305,12 @@ fn get_cybersource_card_type(card_network: common_enums::CardNetwork) -> Option< common_enums::CardNetwork::UnionPay => Some("062"), //"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024" common_enums::CardNetwork::Maestro => Some("042"), - common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay => None, + common_enums::CardNetwork::Interac + | common_enums::CardNetwork::RuPay + | common_enums::CardNetwork::Star + | common_enums::CardNetwork::Accel + | common_enums::CardNetwork::Pulse + | common_enums::CardNetwork::Nyce => None, } } diff --git a/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs index 0cfccd280f4..a967eefbd73 100644 --- a/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs @@ -204,7 +204,11 @@ impl TryFrom<&HipayRouterData<&PaymentsAuthorizeRouterData>> for HipayPaymentsRe Some(CardNetwork::Interac) => "interac".to_string(), Some(CardNetwork::RuPay) => "rupay".to_string(), Some(CardNetwork::Maestro) => "maestro".to_string(), - None => "".to_string(), + Some(CardNetwork::Star) + | Some(CardNetwork::Accel) + | Some(CardNetwork::Pulse) + | Some(CardNetwork::Nyce) + | None => "".to_string(), }, }, amount: item.amount.clone(), diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs index da6ec769363..73d9007706c 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs @@ -1398,7 +1398,11 @@ fn get_stripe_card_network(card_network: common_enums::CardNetwork) -> Option<St | common_enums::CardNetwork::UnionPay | common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay - | common_enums::CardNetwork::Maestro => None, + | common_enums::CardNetwork::Maestro + | common_enums::CardNetwork::Star + | common_enums::CardNetwork::Accel + | common_enums::CardNetwork::Pulse + | common_enums::CardNetwork::Nyce => None, } } diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 9f62dbbe987..4ddb32b4d6c 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -77,6 +77,14 @@ impl PaymentMethodData { pub fn is_network_token_payment_method_data(&self) -> bool { matches!(self, Self::NetworkToken(_)) } + + pub fn get_co_badged_card_data(&self) -> Option<&payment_methods::CoBadgedCardData> { + if let Self::Card(card) = self { + card.co_badged_card_data.as_ref() + } else { + None + } + } } #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] @@ -92,6 +100,7 @@ pub struct Card { pub bank_code: Option<String>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, + pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] @@ -120,6 +129,7 @@ pub struct CardDetail { pub bank_code: Option<String>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, + pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } impl CardDetailsForNetworkTransactionId { @@ -162,6 +172,7 @@ impl From<&Card> for CardDetail { bank_code: item.bank_code.to_owned(), nick_name: item.nick_name.to_owned(), card_holder_name: item.card_holder_name.to_owned(), + co_badged_card_data: item.co_badged_card_data.to_owned(), } } } @@ -723,6 +734,7 @@ impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodData { bank_code: None, nick_name, card_holder_name, + co_badged_card_data: None, })), } } @@ -732,7 +744,7 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData { fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self { match api_model_payment_method_data { api_models::payments::PaymentMethodData::Card(card_data) => { - Self::Card(Card::from(card_data)) + Self::Card(Card::from((card_data, None))) } api_models::payments::PaymentMethodData::CardRedirect(card_redirect) => { Self::CardRedirect(From::from(card_redirect)) @@ -782,8 +794,18 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData { } } -impl From<api_models::payments::Card> for Card { - fn from(value: api_models::payments::Card) -> Self { +impl + From<( + api_models::payments::Card, + Option<payment_methods::CoBadgedCardData>, + )> for Card +{ + fn from( + (value, co_badged_card_data_optional): ( + api_models::payments::Card, + Option<payment_methods::CoBadgedCardData>, + ), + ) -> Self { let api_models::payments::Card { card_number, card_exp_month, @@ -810,6 +832,7 @@ impl From<api_models::payments::Card> for Card { bank_code, nick_name, card_holder_name, + co_badged_card_data: co_badged_card_data_optional, } } } @@ -1875,6 +1898,16 @@ pub enum PaymentMethodsData { NetworkToken(NetworkTokenDetailsPaymentMethod), } +impl PaymentMethodsData { + pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> { + if let Self::Card(card) = self { + card.co_badged_card_data.clone() + } else { + None + } + } +} + #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct NetworkTokenDetailsPaymentMethod { pub last4_digits: Option<String>, @@ -1909,6 +1942,7 @@ pub struct CardDetailsPaymentMethod { pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, + pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -1926,6 +1960,7 @@ impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod { card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, + co_badged_card_data: None, } } } diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs index 955d01c94df..de7d9641449 100644 --- a/crates/hyperswitch_domain_models/src/payment_methods.rs +++ b/crates/hyperswitch_domain_models/src/payment_methods.rs @@ -12,7 +12,11 @@ use common_utils::{ }; use diesel_models::{enums as storage_enums, PaymentMethodUpdate}; use error_stack::ResultExt; +#[cfg(feature = "v1")] +use masking::ExposeInterface; use masking::{PeekInterface, Secret}; +#[cfg(feature = "v1")] +use router_env::logger; #[cfg(feature = "v2")] use rustc_hash::FxHashMap; #[cfg(feature = "v2")] @@ -20,13 +24,11 @@ use serde_json::Value; use time::PrimitiveDateTime; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -use crate::{ - address::Address, payment_method_data as domain_payment_method_data, - type_encryption::OptionalEncryptableJsonType, -}; +use crate::{address::Address, type_encryption::OptionalEncryptableJsonType}; use crate::{ mandates::{self, CommonMandateReference}, merchant_key_store::MerchantKeyStore, + payment_method_data as domain_payment_method_data, type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, }; @@ -131,6 +133,25 @@ impl PaymentMethod { &self.payment_method_id } + #[cfg(feature = "v1")] + pub fn get_payment_methods_data( + &self, + ) -> Option<domain_payment_method_data::PaymentMethodsData> { + self.payment_method_data + .clone() + .map(|value| value.into_inner().expose()) + .and_then(|value| { + serde_json::from_value::<domain_payment_method_data::PaymentMethodsData>(value) + .map_err(|error| { + logger::warn!( + ?error, + "Failed to parse payment method data in payment method info" + ); + }) + .ok() + }) + } + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn get_id(&self) -> &id_type::GlobalPaymentMethodId { &self.id diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 93e4f8e0408..1b5d3392aa2 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -325,6 +325,10 @@ impl IntoDirValue for api_enums::CardNetwork { Self::Interac => Ok(dirval!(CardNetwork = Interac)), Self::RuPay => Ok(dirval!(CardNetwork = RuPay)), Self::Maestro => Ok(dirval!(CardNetwork = Maestro)), + Self::Star => Ok(dirval!(CardNetwork = Star)), + Self::Accel => Ok(dirval!(CardNetwork = Accel)), + Self::Pulse => Ok(dirval!(CardNetwork = Pulse)), + Self::Nyce => Ok(dirval!(CardNetwork = Nyce)), } } } diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rs index 3dc8f3a5e5d..a957d2375b4 100644 --- a/crates/payment_methods/src/core/migration/payment_methods.rs +++ b/crates/payment_methods/src/core/migration/payment_methods.rs @@ -540,8 +540,9 @@ pub async fn skip_locker_call_and_migrate_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; - let payment_method_card_details = - pm_api::PaymentMethodsData::Card(pm_api::CardDetailsPaymentMethod::from(card.clone())); + let payment_method_card_details = pm_api::PaymentMethodsData::Card( + pm_api::CardDetailsPaymentMethod::from((card.clone(), None)), + ); let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = Some( create_encrypted_data( diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 12cc03eb929..49800dd3c89 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -536,6 +536,7 @@ pub(crate) async fn fetch_raw_secrets( platform: conf.platform, authentication_providers: conf.authentication_providers, open_router: conf.open_router, + debit_routing_config: conf.debit_routing_config, clone_connector_allowlist: conf.clone_connector_allowlist, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index c0f2d680d37..34270971efb 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -115,6 +115,7 @@ pub struct Settings<S: SecretState> { #[cfg(feature = "payouts")] pub payouts: Payouts, pub payout_method_filters: ConnectorFilters, + pub debit_routing_config: DebitRoutingConfig, pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>, pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>, pub google_pay_decrypt_keys: Option<GooglePayDecryptConfig>, @@ -156,6 +157,16 @@ pub struct Settings<S: SecretState> { pub clone_connector_allowlist: Option<CloneConnectorAllowlistConfig>, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct DebitRoutingConfig { + #[serde(deserialize_with = "deserialize_hashmap")] + pub connector_supported_debit_networks: HashMap<enums::Connector, HashSet<enums::CardNetwork>>, + #[serde(deserialize_with = "deserialize_hashset")] + pub supported_currencies: HashSet<enums::Currency>, + #[serde(deserialize_with = "deserialize_hashset")] + pub supported_connectors: HashSet<enums::Connector>, +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct OpenRouter { pub enabled: bool, diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index e96aa339e9e..db2122b242c 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -45,6 +45,8 @@ pub mod refunds; #[cfg(feature = "v2")] pub mod refunds_v2; +#[cfg(feature = "v1")] +pub mod debit_routing; pub mod routing; pub mod surcharge_decision_config; #[cfg(feature = "olap")] diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rs index 71cc4bd840f..0e7315c5d4a 100644 --- a/crates/router/src/core/authentication/utils.rs +++ b/crates/router/src/core/authentication/utils.rs @@ -24,28 +24,30 @@ pub fn get_connector_data_if_separate_authn_supported( connector_call_type: &api::ConnectorCallType, ) -> Option<api::ConnectorData> { match connector_call_type { - api::ConnectorCallType::PreDetermined(connector_data) => { - if connector_data + api::ConnectorCallType::PreDetermined(connector_routing_data) => { + if connector_routing_data + .connector_data .connector_name .is_separate_authentication_supported() { - Some(connector_data.clone()) + Some(connector_routing_data.connector_data.clone()) } else { None } } - api::ConnectorCallType::Retryable(connectors) => { - connectors.first().and_then(|connector_data| { - if connector_data + api::ConnectorCallType::Retryable(connector_routing_data) => connector_routing_data + .first() + .and_then(|connector_routing_data| { + if connector_routing_data + .connector_data .connector_name .is_separate_authentication_supported() { - Some(connector_data.clone()) + Some(connector_routing_data.connector_data.clone()) } else { None } - }) - } + }), api::ConnectorCallType::SessionMultiple(_) => None, } } diff --git a/crates/router/src/core/debit_routing.rs b/crates/router/src/core/debit_routing.rs new file mode 100644 index 00000000000..5824946c3e7 --- /dev/null +++ b/crates/router/src/core/debit_routing.rs @@ -0,0 +1,460 @@ +use std::{collections::HashSet, fmt::Debug}; + +use api_models::{enums as api_enums, open_router}; +use common_enums::enums; +use common_utils::id_type; +use error_stack::ResultExt; +use masking::Secret; + +use super::{ + payments::{OperationSessionGetters, OperationSessionSetters}, + routing::TransactionData, +}; +use crate::{ + core::{ + errors, + payments::{operations::BoxedOperation, routing}, + }, + logger, + routes::SessionState, + settings, + types::{ + api::{self, ConnectorCallType}, + domain, + }, +}; + +pub struct DebitRoutingResult { + pub debit_routing_connector_call_type: ConnectorCallType, + pub debit_routing_output: open_router::DebitRoutingOutput, +} + +pub async fn perform_debit_routing<F, Req, D>( + operation: &BoxedOperation<'_, F, Req, D>, + state: &SessionState, + business_profile: &domain::Profile, + payment_data: &mut D, + connector: Option<ConnectorCallType>, +) -> ( + Option<ConnectorCallType>, + Option<open_router::DebitRoutingOutput>, +) +where + F: Send + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, +{ + let mut debit_routing_output = None; + + if should_execute_debit_routing(state, business_profile, operation, payment_data).await { + let debit_routing_config = state.conf.debit_routing_config.clone(); + let debit_routing_supported_connectors = debit_routing_config.supported_connectors.clone(); + + if let Some((call_connector_type, acquirer_country)) = connector + .clone() + .zip(business_profile.merchant_business_country) + { + debit_routing_output = match call_connector_type { + ConnectorCallType::PreDetermined(connector_data) => { + logger::info!("Performing debit routing for PreDetermined connector"); + handle_pre_determined_connector( + state, + &debit_routing_config, + debit_routing_supported_connectors, + &connector_data, + payment_data, + acquirer_country, + ) + .await + } + ConnectorCallType::Retryable(connector_data) => { + logger::info!("Performing debit routing for Retryable connector"); + handle_retryable_connector( + state, + &debit_routing_config, + debit_routing_supported_connectors, + connector_data, + payment_data, + acquirer_country, + ) + .await + } + ConnectorCallType::SessionMultiple(_) => { + logger::info!( + "SessionMultiple connector type is not supported for debit routing" + ); + None + } + #[cfg(feature = "v2")] + ConnectorCallType::Skip => { + logger::info!("Skip connector type is not supported for debit routing"); + None + } + }; + } + } + + if let Some(debit_routing_output) = debit_routing_output { + ( + Some(debit_routing_output.debit_routing_connector_call_type), + Some(debit_routing_output.debit_routing_output), + ) + } else { + // If debit_routing_output is None, return the static routing output (connector) + logger::info!("Debit routing is not performed, returning static routing output"); + (connector, None) + } +} + +async fn should_execute_debit_routing<F, Req, D>( + state: &SessionState, + business_profile: &domain::Profile, + operation: &BoxedOperation<'_, F, Req, D>, + payment_data: &D, +) -> bool +where + F: Send + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, +{ + if business_profile.is_debit_routing_enabled + && state.conf.open_router.enabled + && business_profile.merchant_business_country.is_some() + { + logger::info!("Debit routing is enabled for the profile"); + + let debit_routing_config = &state.conf.debit_routing_config; + + if should_perform_debit_routing_for_the_flow(operation, payment_data, debit_routing_config) + { + let is_debit_routable_connector_present = check_for_debit_routing_connector_in_profile( + state, + business_profile.get_id(), + payment_data, + ) + .await; + + if is_debit_routable_connector_present { + logger::debug!("Debit routable connector is configured for the profile"); + return true; + } + } + } + false +} + +pub fn should_perform_debit_routing_for_the_flow<Op: Debug, F: Clone, D>( + operation: &Op, + payment_data: &D, + debit_routing_config: &settings::DebitRoutingConfig, +) -> bool +where + D: OperationSessionGetters<F> + Send + Sync + Clone, +{ + match format!("{operation:?}").as_str() { + "PaymentConfirm" => { + logger::info!("Checking if debit routing is required"); + let payment_intent = payment_data.get_payment_intent(); + let payment_attempt = payment_data.get_payment_attempt(); + + request_validation(payment_intent, payment_attempt, debit_routing_config) + } + _ => false, + } +} + +pub fn request_validation( + payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, + payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, + debit_routing_config: &settings::DebitRoutingConfig, +) -> bool { + logger::debug!("Validating request for debit routing"); + let is_currency_supported = payment_intent.currency.map(|currency| { + debit_routing_config + .supported_currencies + .contains(&currency) + }); + + payment_intent.setup_future_usage != Some(enums::FutureUsage::OffSession) + && payment_intent.amount.is_greater_than(0) + && is_currency_supported == Some(true) + && payment_attempt.authentication_type != Some(enums::AuthenticationType::ThreeDs) + && payment_attempt.payment_method == Some(enums::PaymentMethod::Card) + && payment_attempt.payment_method_type == Some(enums::PaymentMethodType::Debit) +} + +pub async fn check_for_debit_routing_connector_in_profile< + F: Clone, + D: OperationSessionGetters<F>, +>( + state: &SessionState, + business_profile_id: &id_type::ProfileId, + payment_data: &D, +) -> bool { + logger::debug!("Checking for debit routing connector in profile"); + let debit_routing_supported_connectors = + state.conf.debit_routing_config.supported_connectors.clone(); + + let transaction_data = super::routing::PaymentsDslInput::new( + payment_data.get_setup_mandate(), + payment_data.get_payment_attempt(), + payment_data.get_payment_intent(), + payment_data.get_payment_method_data(), + payment_data.get_address(), + payment_data.get_recurring_details(), + payment_data.get_currency(), + ); + + let fallback_config_optional = super::routing::helpers::get_merchant_default_config( + &*state.clone().store, + business_profile_id.get_string_repr(), + &enums::TransactionType::from(&TransactionData::Payment(transaction_data)), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .map_err(|error| { + logger::warn!(?error, "Failed to fetch default connector for a profile"); + }) + .ok(); + + let is_debit_routable_connector_present = fallback_config_optional + .map(|fallback_config| { + fallback_config.iter().any(|fallback_config_connector| { + debit_routing_supported_connectors.contains(&api_enums::Connector::from( + fallback_config_connector.connector, + )) + }) + }) + .unwrap_or(false); + + is_debit_routable_connector_present +} + +async fn handle_pre_determined_connector<F, D>( + state: &SessionState, + debit_routing_config: &settings::DebitRoutingConfig, + debit_routing_supported_connectors: HashSet<api_enums::Connector>, + connector_data: &api::ConnectorRoutingData, + payment_data: &mut D, + acquirer_country: enums::CountryAlpha2, +) -> Option<DebitRoutingResult> +where + F: Send + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, +{ + if debit_routing_supported_connectors.contains(&connector_data.connector_data.connector_name) { + logger::debug!("Chosen connector is supported for debit routing"); + + let debit_routing_output = + get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?; + + logger::debug!( + "Sorted co-badged networks: {:?}", + debit_routing_output.co_badged_card_networks + ); + + let valid_connectors = build_connector_routing_data( + connector_data, + debit_routing_config, + &debit_routing_output.co_badged_card_networks, + ); + + if !valid_connectors.is_empty() { + return Some(DebitRoutingResult { + debit_routing_connector_call_type: ConnectorCallType::Retryable(valid_connectors), + debit_routing_output, + }); + } + } + + None +} + +pub async fn get_debit_routing_output< + F: Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F>, +>( + state: &SessionState, + payment_data: &mut D, + acquirer_country: enums::CountryAlpha2, +) -> Option<open_router::DebitRoutingOutput> { + logger::debug!("Fetching sorted card networks"); + let payment_attempt = payment_data.get_payment_attempt(); + + let (saved_co_badged_card_data, saved_card_type, card_isin) = + extract_saved_card_info(payment_data); + + match ( + saved_co_badged_card_data + .clone() + .zip(saved_card_type.clone()), + card_isin.clone(), + ) { + (None, None) => { + logger::debug!("Neither co-badged data nor ISIN found; skipping routing"); + None + } + _ => { + let co_badged_card_data = saved_co_badged_card_data + .zip(saved_card_type) + .and_then(|(co_badged, card_type)| { + open_router::DebitRoutingRequestData::try_from((co_badged, card_type)) + .map(Some) + .map_err(|error| { + logger::warn!("Failed to convert co-badged card data: {:?}", error); + }) + .ok() + }) + .flatten(); + + if co_badged_card_data.is_none() && card_isin.is_none() { + logger::debug!("Neither co-badged data nor ISIN found; skipping routing"); + return None; + } + + let co_badged_card_request = open_router::CoBadgedCardRequest { + merchant_category_code: enums::MerchantCategoryCode::Mcc0001, + acquirer_country, + co_badged_card_data, + }; + + routing::perform_open_routing_for_debit_routing( + state, + payment_attempt, + co_badged_card_request, + card_isin, + ) + .await + .map_err(|error| { + logger::warn!(?error, "Debit routing call to open router failed"); + }) + .ok() + } + } +} + +fn extract_saved_card_info<F, D>( + payment_data: &D, +) -> ( + Option<api_models::payment_methods::CoBadgedCardData>, + Option<String>, + Option<Secret<String>>, +) +where + D: OperationSessionGetters<F>, +{ + let payment_method_data_optional = payment_data.get_payment_method_data(); + match payment_data + .get_payment_method_info() + .and_then(|info| info.get_payment_methods_data()) + { + Some(hyperswitch_domain_models::payment_method_data::PaymentMethodsData::Card(card)) => { + match (&card.co_badged_card_data, &card.card_isin) { + (Some(co_badged), _) => { + logger::debug!("Co-badged card data found in saved payment method"); + (Some(co_badged.clone()), card.card_type, None) + } + (None, Some(card_isin)) => { + logger::debug!("No co-badged data; using saved card ISIN"); + (None, None, Some(Secret::new(card_isin.clone()))) + } + _ => (None, None, None), + } + } + _ => match payment_method_data_optional { + Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(card)) => { + logger::debug!("Using card data from payment request"); + ( + None, + None, + Some(Secret::new(card.card_number.get_card_isin())), + ) + } + _ => (None, None, None), + }, + } +} + +fn check_connector_support_for_network( + debit_routing_config: &settings::DebitRoutingConfig, + connector_name: api_enums::Connector, + network: &enums::CardNetwork, +) -> Option<enums::CardNetwork> { + debit_routing_config + .connector_supported_debit_networks + .get(&connector_name) + .and_then(|supported_networks| { + (supported_networks.contains(network) || network.is_global_network()) + .then(|| network.clone()) + }) +} + +fn build_connector_routing_data( + connector_data: &api::ConnectorRoutingData, + debit_routing_config: &settings::DebitRoutingConfig, + fee_sorted_debit_networks: &[enums::CardNetwork], +) -> Vec<api::ConnectorRoutingData> { + fee_sorted_debit_networks + .iter() + .filter_map(|network| { + check_connector_support_for_network( + debit_routing_config, + connector_data.connector_data.connector_name, + network, + ) + .map(|valid_network| api::ConnectorRoutingData { + connector_data: connector_data.connector_data.clone(), + network: Some(valid_network), + }) + }) + .collect() +} + +async fn handle_retryable_connector<F, D>( + state: &SessionState, + debit_routing_config: &settings::DebitRoutingConfig, + debit_routing_supported_connectors: HashSet<api_enums::Connector>, + connector_data_list: Vec<api::ConnectorRoutingData>, + payment_data: &mut D, + acquirer_country: enums::CountryAlpha2, +) -> Option<DebitRoutingResult> +where + F: Send + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, +{ + let is_any_debit_routing_connector_supported = + connector_data_list.iter().any(|connector_data| { + debit_routing_supported_connectors + .contains(&connector_data.connector_data.connector_name) + }); + + if is_any_debit_routing_connector_supported { + let debit_routing_output = + get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?; + + logger::debug!( + "Sorted co-badged networks: {:?}", + debit_routing_output.co_badged_card_networks + ); + + let supported_connectors: Vec<_> = connector_data_list + .iter() + .flat_map(|connector_data| { + build_connector_routing_data( + connector_data, + debit_routing_config, + &debit_routing_output.co_badged_card_networks, + ) + }) + .collect(); + + if !supported_connectors.is_empty() { + return Some(DebitRoutingResult { + debit_routing_connector_call_type: ConnectorCallType::Retryable( + supported_connectors, + ), + debit_routing_output, + }); + } + } + + None +} diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 221390e573f..0b4590b2bec 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -780,6 +780,11 @@ pub(crate) async fn get_payment_method_create_request( Some(pm_data) => match payment_method { Some(payment_method) => match pm_data { domain::PaymentMethodData::Card(card) => { + let card_network = get_card_network_with_us_local_debit_network_override( + card.card_network.clone(), + card.co_badged_card_data.as_ref(), + ); + let card_detail = payment_methods::CardDetail { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), @@ -787,7 +792,7 @@ pub(crate) async fn get_payment_method_create_request( card_holder_name: billing_name, nick_name: card.nick_name.clone(), card_issuing_country: card.card_issuing_country.clone(), - card_network: card.card_network.clone(), + card_network: card_network.clone(), card_issuer: card.card_issuer.clone(), card_type: card.card_type.clone(), }; @@ -803,8 +808,8 @@ pub(crate) async fn get_payment_method_create_request( card: Some(card_detail), metadata: None, customer_id: customer_id.clone(), - card_network: card - .card_network + card_network: card_network + .clone() .as_ref() .map(|card_network| card_network.to_string()), client_secret: None, @@ -852,6 +857,32 @@ pub(crate) async fn get_payment_method_create_request( } } +/// Determines the appropriate card network to to be stored. +/// +/// If the provided card network is a US local network, this function attempts to +/// override it with the first global network from the co-badged card data, if available. +/// Otherwise, it returns the original card network as-is. +/// +fn get_card_network_with_us_local_debit_network_override( + card_network: Option<common_enums::CardNetwork>, + co_badged_card_data: Option<&payment_methods::CoBadgedCardData>, +) -> Option<common_enums::CardNetwork> { + if let Some(true) = card_network + .as_ref() + .map(|network| network.is_us_local_network()) + { + services::logger::debug!("Card network is a US local network, checking for global network in co-badged card data"); + co_badged_card_data.and_then(|data| { + data.co_badged_card_networks + .iter() + .find(|network| network.is_global_network()) + .cloned() + }) + } else { + card_network + } +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn create_payment_method( diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index a11562c7c26..6c2c2cb0739 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -424,7 +424,7 @@ impl PaymentMethodsController for PmCards<'_> { logger::debug!("Network token added to locker"); let (token_pm_resp, _duplication_check) = resp; let pm_token_details = token_pm_resp.card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) + PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None))) }); let pm_network_token_data_encrypted = pm_token_details .async_map(|pm_card| { @@ -502,10 +502,9 @@ impl PaymentMethodsController for PmCards<'_> { network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, ) -> errors::RouterResult<domain::PaymentMethod> { - let pm_card_details = resp - .card - .clone() - .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + let pm_card_details = resp.card.clone().map(|card| { + PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None))) + }); let key_manager_state = self.state.into(); let pm_data_encrypted: crypto::OptionalEncryptableValue = pm_card_details .clone() @@ -1278,7 +1277,10 @@ impl PaymentMethodsController for PmCards<'_> { }); let updated_pmd = updated_card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( + card.clone(), + None, + ))) }); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd @@ -1593,6 +1595,7 @@ pub async fn add_payment_method_data( card_issuer: card_info.as_ref().and_then(|ci| ci.card_issuer.clone()), card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()), saved_to_locker: true, + co_badged_card_data: None, }; let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> = create_encrypted_data( @@ -1836,9 +1839,9 @@ pub async fn update_customer_payment_method( saved_to_locker: true, }); - let updated_pmd = updated_card - .as_ref() - .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + let updated_pmd = updated_card.as_ref().map(|card| { + PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None))) + }); let key_manager_state = (&state).into(); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd .async_map(|updated_pmd| { diff --git a/crates/router/src/core/payment_methods/tokenize.rs b/crates/router/src/core/payment_methods/tokenize.rs index cc27e813b5c..98eca478c93 100644 --- a/crates/router/src/core/payment_methods/tokenize.rs +++ b/crates/router/src/core/payment_methods/tokenize.rs @@ -272,6 +272,7 @@ where card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker, + co_badged_card_data: card_details.co_badged_card_data.clone(), }); create_encrypted_data(&self.state.into(), self.key_store, pm_data) .await @@ -297,6 +298,7 @@ where card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker, + co_badged_card_data: None, }); create_encrypted_data(&self.state.into(), self.key_store, token_data) .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 b714bdb9a6b..2537a244a58 100644 --- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs +++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs @@ -132,6 +132,7 @@ impl<'a> NetworkTokenizationBuilder<'a, CardRequestValidated> { .map_or(card_req.card_issuing_country.clone(), |card_info| { card_info.card_issuing_country.clone() }), + co_badged_card_data: None, }; NetworkTokenizationBuilder { state: std::marker::PhantomData, diff --git a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs index 2249434b107..a55896b36c5 100644 --- a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs +++ b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs @@ -151,6 +151,7 @@ impl<'a> NetworkTokenizationBuilder<'a, PmValidated> { card_issuing_country: optional_card_info .as_ref() .and_then(|card_info| card_info.card_issuing_country.clone()), + co_badged_card_data: None, }; NetworkTokenizationBuilder { state: std::marker::PhantomData, diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 2231f7d89f6..af60d07a466 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -121,6 +121,7 @@ impl Vaultable for domain::Card { card_type: None, nick_name: value1.nickname.map(masking::Secret::new), card_holder_name: value1.card_holder_name, + co_badged_card_data: None, }; let supp_data = SupplementaryVaultData { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d166bc41a24..cb68ece2039 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -88,9 +88,11 @@ use self::{ use super::{ errors::StorageErrorExt, payment_methods::surcharge_decision_configs, routing::TransactionData, }; +#[cfg(feature = "v1")] +use crate::core::debit_routing; #[cfg(feature = "frm")] use crate::core::fraud_check as frm_core; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[cfg(feature = "v1")] use crate::core::routing::helpers as routing_helpers; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use crate::types::api::convert_connector_data_to_routable_connectors; @@ -197,7 +199,7 @@ where state, req_state.clone(), &merchant_context, - connector_data.clone(), + connector_data.connector_data.clone(), &operation, &mut payment_data, &customer, @@ -353,6 +355,15 @@ where ) .await?; + let (connector, debit_routing_output) = debit_routing::perform_debit_routing( + &operation, + state, + &business_profile, + &mut payment_data, + connector, + ) + .await; + let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data); let locale = header_payload.locale.clone(); @@ -487,7 +498,7 @@ where let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( &*state.store, - connector.connector.id(), + connector.connector_data.connector.id(), merchant_context.get_merchant_account().get_id(), 0, ) @@ -501,7 +512,7 @@ where state, req_state.clone(), merchant_context, - connector.clone(), + connector.connector_data.clone(), &operation, &mut payment_data, &customer, @@ -516,6 +527,7 @@ where &business_profile, false, false, + None, ) .await?; @@ -579,7 +591,7 @@ where merchant_context, &customer, &mca, - connector, + &connector.connector_data, &mut payment_data, op_ref, Some(header_payload.clone()), @@ -599,7 +611,12 @@ where let mut connectors = connectors.clone().into_iter(); - let connector_data = get_connector_data(&mut connectors)?; + let (connector_data, routing_decision) = + get_connector_data_with_routing_decision( + &mut connectors, + &business_profile, + debit_routing_output, + )?; let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( @@ -633,6 +650,7 @@ where &business_profile, false, false, + routing_decision, ) .await?; @@ -1018,9 +1036,10 @@ where add_connector_http_status_code_metrics(connector_http_status_code); #[cfg(all(feature = "dynamic_routing", feature = "v1"))] - let routable_connectors = convert_connector_data_to_routable_connectors(&[connector.clone()]) - .map_err(|e| logger::error!(routable_connector_error=?e)) - .unwrap_or_default(); + let routable_connectors = + convert_connector_data_to_routable_connectors(&[connector.clone().into()]) + .map_err(|e| logger::error!(routable_connector_error=?e)) + .unwrap_or_default(); let mut payment_data = operation .to_post_update_tracker()? @@ -1126,7 +1145,7 @@ where state, req_state.clone(), &merchant_context, - connector_data.clone(), + connector_data.connector_data.clone(), &operation, &mut payment_data, call_connector_action.clone(), @@ -1404,14 +1423,50 @@ where #[inline] pub fn get_connector_data( - connectors: &mut IntoIter<api::ConnectorData>, -) -> RouterResult<api::ConnectorData> { + connectors: &mut IntoIter<api::ConnectorRoutingData>, +) -> RouterResult<api::ConnectorRoutingData> { connectors .next() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector not found in connectors iterator") } +#[cfg(feature = "v1")] +pub fn get_connector_with_networks( + connectors: &mut IntoIter<api::ConnectorRoutingData>, +) -> Option<(api::ConnectorData, enums::CardNetwork)> { + connectors.find_map(|connector| { + connector + .network + .map(|network| (connector.connector_data, network)) + }) +} + +#[cfg(feature = "v1")] +fn get_connector_data_with_routing_decision( + connectors: &mut IntoIter<api::ConnectorRoutingData>, + business_profile: &domain::Profile, + debit_routing_output_optional: Option<api_models::open_router::DebitRoutingOutput>, +) -> RouterResult<( + api::ConnectorData, + Option<routing_helpers::RoutingDecisionData>, +)> { + if business_profile.is_debit_routing_enabled && debit_routing_output_optional.is_some() { + if let Some((data, card_network)) = get_connector_with_networks(connectors) { + let debit_routing_output = + debit_routing_output_optional.get_required_value("debit routing output")?; + let routing_decision = + routing_helpers::RoutingDecisionData::get_debit_routing_decision_data( + card_network, + debit_routing_output, + ); + return Ok((data, Some(routing_decision))); + } + } + + Ok((get_connector_data(connectors)?.connector_data, None)) +} + #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn call_surcharge_decision_management_for_session_flow( @@ -3013,6 +3068,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( business_profile: &domain::Profile, is_retry_payment: bool, should_retry_with_pan: bool, + routing_decision: Option<routing_helpers::RoutingDecisionData>, ) -> RouterResult<( RouterData<F, RouterDReq, router_types::PaymentsResponseData>, helpers::MerchantConnectorAccountType, @@ -3075,6 +3131,10 @@ where .await?; *payment_data = pd; + // This is used to apply any kind of routing decision to the required data, + // before the call to `connector` is made. + routing_decision.map(|decision| decision.apply_routing_decision(payment_data)); + // Validating the blocklist guard and generate the fingerprint blocklist_guard(state, merchant_context, operation, payment_data).await?; @@ -6434,7 +6494,7 @@ where .attach_printable("Invalid connector name received in 'routed_through'")?; routing_data.routed_through = Some(connector_name.clone()); - return Ok(ConnectorCallType::PreDetermined(connector_data)); + return Ok(ConnectorCallType::PreDetermined(connector_data.into())); } if let Some(mandate_connector_details) = payment_data.get_mandate_connector().as_ref() { @@ -6453,7 +6513,7 @@ where .merchant_connector_id .clone_from(&mandate_connector_details.merchant_connector_id); - return Ok(ConnectorCallType::PreDetermined(connector_data)); + return Ok(ConnectorCallType::PreDetermined(connector_data.into())); } if let Some((pre_routing_results, storage_pm_type)) = @@ -6497,7 +6557,8 @@ where connector_choice.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid connector name received")?; + .attach_printable("Invalid connector name received")? + .into(); pre_routing_connector_data_list.push(connector_data); } @@ -6664,7 +6725,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone state: &SessionState, payment_data: &mut D, routing_data: &mut storage::RoutingData, - connectors: Vec<api::ConnectorData>, + connectors: Vec<api::ConnectorRoutingData>, mandate_type: Option<api::MandateTransactionType>, is_connector_agnostic_mit_enabled: Option<bool>, is_network_tokenization_enabled: bool, @@ -6751,12 +6812,16 @@ where "no eligible connector found for token-based MIT payment", )?; - routing_data.routed_through = - Some(chosen_connector_data.connector_name.to_string()); + routing_data.routed_through = Some( + chosen_connector_data + .connector_data + .connector_name + .to_string(), + ); routing_data .merchant_connector_id - .clone_from(&chosen_connector_data.merchant_connector_id); + .clone_from(&chosen_connector_data.connector_data.merchant_connector_id); payment_data.set_mandate_id(payments_api::MandateIds { mandate_id: None, @@ -6788,16 +6853,20 @@ where Some(api::MandateTransactionType::RecurringMandateTransaction), ) => { if let Some(connector) = connectors.first() { + let connector = &connector.connector_data; routing_data.routed_through = Some(connector.connector_name.clone().to_string()); routing_data .merchant_connector_id .clone_from(&connector.merchant_connector_id); - Ok(ConnectorCallType::PreDetermined(api::ConnectorData { - connector: connector.connector.clone(), - connector_name: connector.connector_name, - get_token: connector.get_token.clone(), - merchant_connector_id: connector.merchant_connector_id.clone(), - })) + Ok(ConnectorCallType::PreDetermined( + api::ConnectorData { + connector: connector.connector.clone(), + connector_name: connector.connector_name, + get_token: connector.get_token.clone(), + merchant_connector_id: connector.merchant_connector_id.clone(), + } + .into(), + )) } else { logger::error!("no eligible connector found for the ppt_mandate payment"); Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration.into()) @@ -6813,9 +6882,10 @@ where .attach_printable("no eligible connector found for payment")? .clone(); - routing_data.routed_through = Some(first_choice.connector_name.to_string()); + routing_data.routed_through = + Some(first_choice.connector_data.connector_name.to_string()); - routing_data.merchant_connector_id = first_choice.merchant_connector_id; + routing_data.merchant_connector_id = first_choice.connector_data.merchant_connector_id; Ok(ConnectorCallType::Retryable(connectors)) } @@ -6847,7 +6917,7 @@ pub async fn decide_connector_for_normal_or_recurring_payment<F: Clone, D>( state: &SessionState, payment_data: &mut D, routing_data: &mut storage::RoutingData, - connectors: Vec<api::ConnectorData>, + connectors: Vec<api::ConnectorRoutingData>, is_connector_agnostic_mit_enabled: Option<bool>, payment_method_info: &domain::PaymentMethod, ) -> RouterResult<ConnectorCallType> @@ -6863,7 +6933,8 @@ where let mut connector_choice = None; - for connector_data in connectors { + for connector_info in connectors { + let connector_data = connector_info.connector_data; let merchant_connector_id = connector_data .merchant_connector_id .as_ref() @@ -6897,11 +6968,12 @@ where )?; let mandate_reference_id = Some(payments_api::MandateReferenceId::ConnectorMandateId( api_models::payments::ConnectorMandateReferenceId::new( - Some(mandate_reference_record.connector_mandate_id.clone()), // connector_mandate_id - Some(payment_method_info.get_id().clone()), // payment_method_id - None, // update_history - mandate_reference_record.mandate_metadata.clone(), // mandate_metadata - mandate_reference_record.connector_mandate_request_reference_id.clone(), // connector_mandate_request_reference_id + Some(mandate_reference_record.connector_mandate_id.clone()), + Some(payment_method_info.get_id().clone()), + // update_history + None, + mandate_reference_record.mandate_metadata.clone(), + mandate_reference_record.connector_mandate_request_reference_id.clone(), ) )); payment_data.set_recurring_mandate_payment_data( @@ -6959,16 +7031,18 @@ where mandate_reference_id, }); - Ok(ConnectorCallType::PreDetermined(chosen_connector_data)) + Ok(ConnectorCallType::PreDetermined( + chosen_connector_data.into(), + )) } pub fn filter_ntid_supported_connectors( - connectors: Vec<api::ConnectorData>, + connectors: Vec<api::ConnectorRoutingData>, ntid_supported_connectors: &HashSet<enums::Connector>, -) -> Vec<api::ConnectorData> { +) -> Vec<api::ConnectorRoutingData> { connectors .into_iter() - .filter(|data| ntid_supported_connectors.contains(&data.connector_name)) + .filter(|data| ntid_supported_connectors.contains(&data.connector_data.connector_name)) .collect() } @@ -6991,12 +7065,14 @@ pub enum ActionType { } pub fn filter_network_tokenization_supported_connectors( - connectors: Vec<api::ConnectorData>, + connectors: Vec<api::ConnectorRoutingData>, network_tokenization_supported_connectors: &HashSet<enums::Connector>, -) -> Vec<api::ConnectorData> { +) -> Vec<api::ConnectorRoutingData> { connectors .into_iter() - .filter(|data| network_tokenization_supported_connectors.contains(&data.connector_name)) + .filter(|data| { + network_tokenization_supported_connectors.contains(&data.connector_data.connector_name) + }) .collect() } @@ -7006,7 +7082,7 @@ pub async fn decide_action_type( is_connector_agnostic_mit_enabled: Option<bool>, is_network_tokenization_enabled: bool, payment_method_info: &domain::PaymentMethod, - filtered_nt_supported_connectors: Vec<api::ConnectorData>, //network tokenization supported connectors + filtered_nt_supported_connectors: Vec<api::ConnectorRoutingData>, //network tokenization supported connectors ) -> Option<ActionType> { match ( is_network_token_with_network_transaction_id_flow( @@ -7351,6 +7427,7 @@ where api::GetToken::Connector, conn.merchant_connector_id, ) + .map(|connector_data| connector_data.into()) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -7440,6 +7517,7 @@ pub async fn route_connector_v1_for_payouts( api::GetToken::Connector, conn.merchant_connector_id, ) + .map(|connector_data| connector_data.into()) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -7970,7 +8048,6 @@ pub trait PaymentMethodChecker<F> { fn should_update_in_post_update_tracker(&self) -> bool; fn should_update_in_update_tracker(&self) -> bool; } - #[cfg(feature = "v1")] impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> { fn should_update_in_post_update_tracker(&self) -> bool { @@ -8066,6 +8143,11 @@ pub trait OperationSessionSetters<F> { &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ); + fn set_card_network(&mut self, card_network: enums::CardNetwork); + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ); #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod); fn set_frm_message(&mut self, frm_message: FraudCheck); @@ -8298,6 +8380,31 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> { self.payment_attempt.merchant_connector_id = merchant_connector_id; } + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + if let Some(domain::PaymentMethodData::Card(card)) = &mut self.payment_method_data { + logger::debug!("set card network {:?}", card_network.clone()); + card.card_network = Some(card_network); + }; + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { + let co_badged_card_data = + api_models::payment_methods::CoBadgedCardData::from(debit_routing_ouput); + let card_type = debit_routing_ouput + .card_type + .clone() + .to_string() + .to_uppercase(); + if let Some(domain::PaymentMethodData::Card(card)) = &mut self.payment_method_data { + card.co_badged_card_data = Some(co_badged_card_data); + card.card_type = Some(card_type); + logger::debug!("set co-badged card data in payment method data"); + }; + } + #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod) { self.payment_attempt.capture_method = Some(capture_method); @@ -8523,6 +8630,17 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { todo!() } + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { + todo!() + } + fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } @@ -8763,6 +8881,17 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { todo!() } + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { + todo!() + } + fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) { todo!() } @@ -8975,6 +9104,17 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { todo!() } + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { + todo!() + } + fn set_pm_token(&mut self, _token: String) { todo!() } @@ -9197,6 +9337,17 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { todo!() } + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { + todo!() + } + fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 59b25d9b86b..0cada8c368e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2120,6 +2120,11 @@ pub async fn retrieve_payment_method_data_with_permanent_token( .network_token_requestor_reference_id .clone(), ); + + let co_badged_card_data = payment_method_info + .get_payment_methods_data() + .and_then(|payment_methods_data| payment_methods_data.get_co_badged_card_data()); + match vault_fetch_action { VaultFetchAction::FetchCardDetailsFromLocker => { let card = vault_data @@ -2132,6 +2137,7 @@ pub async fn retrieve_payment_method_data_with_permanent_token( &payment_intent.merchant_id, locker_id, card_token_data, + co_badged_card_data, ) .await }) @@ -2182,6 +2188,7 @@ pub async fn retrieve_payment_method_data_with_permanent_token( &payment_intent.merchant_id, locker_id, card_token_data, + co_badged_card_data, ) .await }) @@ -2246,6 +2253,7 @@ pub async fn retrieve_card_with_permanent_token_for_external_authentication( &payment_intent.merchant_id, locker_id, card_token_data, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2263,7 +2271,9 @@ pub async fn fetch_card_details_from_locker( 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) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2308,7 +2318,7 @@ pub async fn fetch_card_details_from_locker( card_issuing_country: None, bank_code: None, }; - Ok(api_card.into()) + Ok(domain::Card::from((api_card, co_badged_card_data))) } #[cfg(all( @@ -4584,15 +4594,32 @@ pub async fn get_additional_payment_data( _ => None, }; - let card_network = match card_data + // Added an additional check for card_data.co_badged_card_data.is_some() + // because is_cobadged_card() only returns true if the card number matches a specific regex. + // However, this regex does not cover all possible co-badged networks. + // The co_badged_card_data field is populated based on a co-badged BIN lookup + // and helps identify co-badged cards that may not match the regex alone. + // Determine the card network based on cobadge detection and co-badged BIN data + let is_cobadged_based_on_regex = card_data .card_number .is_cobadged_card() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Card cobadge check failed due to an invalid card network regex", - )? { - true => card_data.card_network.clone(), - false => None, + )?; + + let card_network = match ( + is_cobadged_based_on_regex, + card_data.co_badged_card_data.is_some(), + ) { + (false, false) => { + logger::debug!("Card network is not cobadged"); + None + } + _ => { + logger::debug!("Card network is cobadged"); + card_data.card_network.clone() + } }; let last4 = Some(card_data.card_number.get_last4()); @@ -5170,10 +5197,10 @@ pub async fn get_apple_pay_retryable_connectors<F, D>( state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &D, - pre_routing_connector_data_list: &[api::ConnectorData], + pre_routing_connector_data_list: &[api::ConnectorRoutingData], merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>, business_profile: domain::Profile, -) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse> +) -> CustomResult<Option<Vec<api::ConnectorRoutingData>>, errors::ApiErrorResponse> where F: Send + Clone, D: payments::OperationSessionGetters<F> + Send, @@ -5190,7 +5217,10 @@ where payment_data.get_creds_identifier(), merchant_context.get_merchant_key_store(), profile_id, - &pre_decided_connector_data_first.connector_name.to_string(), + &pre_decided_connector_data_first + .connector_data + .connector_name + .to_string(), merchant_connector_id, ) .await?; @@ -5225,19 +5255,22 @@ where merchant_connector_account.metadata.clone(), Some(&merchant_connector_account.connector_name), )? { - let connector_data = api::ConnectorData::get_connector_by_name( - &state.conf.connectors, - &merchant_connector_account.connector_name.to_string(), - api::GetToken::Connector, - Some(merchant_connector_account.get_id()), - ) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid connector name received")?; + let routing_data: api::ConnectorRoutingData = + api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &merchant_connector_account.connector_name.to_string(), + api::GetToken::Connector, + Some(merchant_connector_account.get_id()), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received")? + .into(); if !connector_data_list.iter().any(|connector_details| { - connector_details.merchant_connector_id == connector_data.merchant_connector_id + connector_details.connector_data.merchant_connector_id + == routing_data.connector_data.merchant_connector_id }) { - connector_data_list.push(connector_data) + connector_data_list.push(routing_data) } } } @@ -5260,7 +5293,7 @@ where let mut routing_connector_data_list = Vec::new(); pre_routing_connector_data_list.iter().for_each(|pre_val| { - routing_connector_data_list.push(pre_val.merchant_connector_id.clone()) + routing_connector_data_list.push(pre_val.connector_data.merchant_connector_id.clone()) }); fallback_connetors_list.iter().for_each(|fallback_val| { @@ -5281,7 +5314,7 @@ where .iter() .for_each(|merchant_connector_id| { let connector_data = connector_data_list.iter().find(|connector_data| { - *merchant_connector_id == connector_data.merchant_connector_id + *merchant_connector_id == connector_data.connector_data.merchant_connector_id }); if let Some(connector_data_details) = connector_data { ordered_connector_data_list.push(connector_data_details.clone()); diff --git a/crates/router/src/core/payments/operations/payment_capture_v2.rs b/crates/router/src/core/payments/operations/payment_capture_v2.rs index ecdf4365970..9fe4e805f94 100644 --- a/crates/router/src/core/payments/operations/payment_capture_v2.rs +++ b/crates/router/src/core/payments/operations/payment_capture_v2.rs @@ -288,7 +288,7 @@ impl<F: Clone + Send> Domain<F, PaymentsCaptureRequest, PaymentCaptureData<F>> f .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; - Ok(ConnectorCallType::PreDetermined(connector_data)) + Ok(ConnectorCallType::PreDetermined(connector_data.into())) } } 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 37cb3875b90..2074b28fd00 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -365,7 +365,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConf Some(merchant_connector_id), )?; - Ok(ConnectorCallType::PreDetermined(connector_data)) + Ok(ConnectorCallType::PreDetermined(connector_data.into())) } } diff --git a/crates/router/src/core/payments/operations/payment_get.rs b/crates/router/src/core/payments/operations/payment_get.rs index 14c4b15052b..05536c56296 100644 --- a/crates/router/src/core/payments/operations/payment_get.rs +++ b/crates/router/src/core/payments/operations/payment_get.rs @@ -293,7 +293,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRetrieveRequest, PaymentStatusDat .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; - Ok(ConnectorCallType::PreDetermined(connector_data)) + Ok(ConnectorCallType::PreDetermined(connector_data.into())) } None | Some(_) => Ok(ConnectorCallType::Skip), } diff --git a/crates/router/src/core/payments/operations/proxy_payments_intent.rs b/crates/router/src/core/payments/operations/proxy_payments_intent.rs index 5d6717b8ca2..1d7fb108b30 100644 --- a/crates/router/src/core/payments/operations/proxy_payments_intent.rs +++ b/crates/router/src/core/payments/operations/proxy_payments_intent.rs @@ -318,7 +318,7 @@ impl<F: Clone + Send + Sync> Domain<F, ProxyPaymentsRequest, PaymentConfirmData< merchant_connector_id, )?; - Ok(ConnectorCallType::PreDetermined(connector_data)) + Ok(ConnectorCallType::PreDetermined(connector_data.into())) } else { Err(error_stack::Report::new( errors::ApiErrorResponse::InternalServerError, diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 5fde726a21b..bfe2c99855e 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -34,7 +34,7 @@ pub async fn do_gsm_actions<F, ApiRequest, FData, D>( state: &app::SessionState, req_state: ReqState, payment_data: &mut D, - mut connectors: IntoIter<api::ConnectorData>, + mut connector_routing_data: IntoIter<api::ConnectorRoutingData>, original_connector_data: &api::ConnectorData, mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>, merchant_context: &domain::MerchantContext, @@ -137,7 +137,7 @@ where break; } - if connectors.len() == 0 { + if connector_routing_data.len() == 0 { logger::info!("connectors exhausted for auto_retry payment"); metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]); break; @@ -159,7 +159,7 @@ where // If should_retry_with_pan is true, it indicates that we are retrying with PAN using the same connector. original_connector_data.clone() } else { - super::get_connector_data(&mut connectors)? + super::get_connector_data(&mut connector_routing_data)?.connector_data }; router_data = do_retry( @@ -372,6 +372,7 @@ where business_profile, true, should_retry_with_pan, + None, ) .await?; diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 9280415412d..b485cd9d987 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1,27 +1,24 @@ mod transformers; pub mod utils; - #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use std::collections::hash_map; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use std::hash::{Hash, Hasher}; use std::{collections::HashMap, str::FromStr, sync::Arc}; +#[cfg(feature = "v1")] +use api_models::open_router::{self as or_types, DecidedGateway, OpenRouterDecideGatewayRequest}; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use api_models::routing as api_routing; use api_models::{ admin as admin_api, enums::{self as api_enums, CountryAlpha2}, routing::ConnectorSelection, }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use api_models::{ - open_router::{self as or_types, DecidedGateway, OpenRouterDecideGatewayRequest}, - routing as api_routing, -}; +use common_utils::ext_traits::AsyncExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use common_utils::{ - ext_traits::{AsyncExt, BytesExt}, - request, -}; +use common_utils::{ext_traits::BytesExt, request}; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use euclid::{ @@ -43,7 +40,7 @@ use kgraph_utils::{ transformers::{IntoContext, IntoDirValue}, types::CountryCurrencyFilter, }; -use masking::PeekInterface; +use masking::{PeekInterface, Secret}; use rand::distributions::{self, Distribution}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use rand::SeedableRng; @@ -57,11 +54,13 @@ use utils::perform_decision_euclid_routing; use crate::core::admin; #[cfg(feature = "payouts")] use crate::core::payouts; +#[cfg(feature = "v1")] +use crate::core::routing::transformers::OpenRouterDecideGatewayRequestExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use crate::{core::routing::transformers::OpenRouterDecideGatewayRequestExt, headers, services}; +use crate::headers; use crate::{ - core::{errors, errors as oss_errors, routing}, - logger, + core::{errors, errors as oss_errors, payments::routing::utils::EuclidApiHandler, routing}, + logger, services, types::{ api::{self, routing as routing_types}, domain, storage as oss_storage, @@ -1580,6 +1579,64 @@ pub async fn perform_dynamic_routing_with_open_router( Ok(connectors) } +#[cfg(feature = "v1")] +pub async fn perform_open_routing_for_debit_routing( + state: &SessionState, + payment_attempt: &oss_storage::PaymentAttempt, + co_badged_card_request: or_types::CoBadgedCardRequest, + card_isin: Option<Secret<String>>, +) -> RoutingResult<or_types::DebitRoutingOutput> { + logger::debug!( + "performing debit routing with open_router for profile {}", + payment_attempt.profile_id.get_string_repr() + ); + + let metadata = Some( + serde_json::to_string(&co_badged_card_request) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode Vaulting data to string") + .change_context(errors::RoutingError::MetadataParsingError)?, + ); + + let open_router_req_body = OpenRouterDecideGatewayRequest::construct_debit_request( + payment_attempt, + metadata, + card_isin, + Some(or_types::RankingAlgorithm::NtwBasedRouting), + ); + + let response: RoutingResult<DecidedGateway> = utils::EuclidApiClient::send_euclid_request( + state, + services::Method::Post, + "decide-gateway", + Some(open_router_req_body), + None, + ) + .await; + + let output = match response { + Ok(decided_gateway) => { + let debit_routing_output = decided_gateway + .debit_routing_output + .get_required_value("debit_routing_output") + .change_context(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + )) + .attach_printable("debit_routing_output is missing in the open routing response")?; + + Ok(debit_routing_output) + } + Err(error_response) => { + logger::error!("open_router_error_response: {:?}", error_response); + Err(errors::RoutingError::OpenRouterError( + "Failed to perform debit routing in open router".into(), + )) + } + }?; + + Ok(output) +} + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn perform_dynamic_routing_with_intelligent_router( state: &SessionState, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 25008523633..ae68ea53773 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -204,6 +204,11 @@ where payment_method_billing_address, ) .await?; + let payment_methods_data = + &save_payment_method_data.request.get_payment_method_data(); + + let co_badged_card_data = payment_methods_data.get_co_badged_card_data(); + let customer_id = customer_id.to_owned().get_required_value("customer_id")?; let merchant_id = merchant_context.get_merchant_account().get_id(); let is_network_tokenization_enabled = @@ -272,7 +277,7 @@ where save_payment_method_data.request.get_payment_method_data(), ) { (Some(card), _) => Some(PaymentMethodsData::Card( - CardDetailsPaymentMethod::from(card.clone()), + CardDetailsPaymentMethod::from((card.clone(), co_badged_card_data)), )), ( _, @@ -303,7 +308,10 @@ where > = match network_token_resp { Some(token_resp) => { let pm_token_details = token_resp.card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( + card.clone(), + None, + ))) }); pm_token_details @@ -645,9 +653,10 @@ where }); let updated_pmd = updated_card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from( + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( card.clone(), - )) + co_badged_card_data, + ))) }); let pm_data_encrypted: Option< Encryptable<Secret<serde_json::Value>>, diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 55b25a0ed36..87888ab4257 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -82,8 +82,8 @@ pub struct PayoutData { // ********************************************** CORE FLOWS ********************************************** pub fn get_next_connector( - connectors: &mut IntoIter<api::ConnectorData>, -) -> RouterResult<api::ConnectorData> { + connectors: &mut IntoIter<api::ConnectorRoutingData>, +) -> RouterResult<api::ConnectorRoutingData> { connectors .next() .ok_or(errors::ApiErrorResponse::InternalServerError) @@ -170,11 +170,11 @@ pub async fn make_connector_decision( payout_data: &mut PayoutData, ) -> RouterResult<()> { match connector_call_type { - api::ConnectorCallType::PreDetermined(connector_data) => { + api::ConnectorCallType::PreDetermined(routing_data) => { Box::pin(call_connector_payout( state, merchant_context, - &connector_data, + &routing_data.connector_data, payout_data, )) .await?; @@ -191,7 +191,7 @@ pub async fn make_connector_decision( if config_bool && payout_data.should_call_gsm() { Box::pin(retry::do_gsm_single_connector_actions( state, - connector_data, + routing_data.connector_data, payout_data, merchant_context, )) @@ -201,10 +201,10 @@ pub async fn make_connector_decision( Ok(()) } - api::ConnectorCallType::Retryable(connectors) => { - let mut connectors = connectors.into_iter(); + api::ConnectorCallType::Retryable(routing_data) => { + let mut routing_data = routing_data.into_iter(); - let connector_data = get_next_connector(&mut connectors)?; + let connector_data = get_next_connector(&mut routing_data)?.connector_data; Box::pin(call_connector_payout( state, @@ -226,7 +226,7 @@ pub async fn make_connector_decision( if config_multiple_connector_bool && payout_data.should_call_gsm() { Box::pin(retry::do_gsm_multiple_connector_actions( state, - connectors, + routing_data, connector_data.clone(), payout_data, merchant_context, @@ -1799,10 +1799,15 @@ pub async fn complete_payout_retrieve( payout_data: &mut PayoutData, ) -> RouterResult<()> { match connector_call_type { - api::ConnectorCallType::PreDetermined(connector_data) => { - create_payout_retrieve(state, merchant_context, &connector_data, payout_data) - .await - .attach_printable("Payout retrieval failed for given Payout request")?; + api::ConnectorCallType::PreDetermined(routing_data) => { + create_payout_retrieve( + state, + merchant_context, + &routing_data.connector_data, + payout_data, + ) + .await + .attach_printable("Payout retrieval failed for given Payout request")?; } api::ConnectorCallType::Retryable(_) | api::ConnectorCallType::SessionMultiple(_) => { Err(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 010331090d0..b157fb0e557 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -495,6 +495,7 @@ pub async fn save_payout_data_to_locker( card_network: card_info.card_network, card_type: card_info.card_type, saved_to_locker: true, + co_badged_card_data: None, }, ) }) @@ -515,6 +516,7 @@ pub async fn save_payout_data_to_locker( card_network: None, card_type: None, saved_to_locker: true, + co_badged_card_data: None, }, ) }); @@ -847,7 +849,7 @@ pub async fn decide_payout_connector( .attach_printable("Invalid connector name received in 'routed_through'")?; routing_data.routed_through = Some(connector_name.clone()); - return Ok(api::ConnectorCallType::PreDetermined(connector_data)); + return Ok(api::ConnectorCallType::PreDetermined(connector_data.into())); } // Validate and get the business_profile from payout_attempt @@ -897,6 +899,7 @@ pub async fn decide_payout_connector( api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) + .map(|connector_data| connector_data.into()) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -947,6 +950,7 @@ pub async fn decide_payout_connector( api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) + .map(|connector_data| connector_data.into()) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs index 3e0697bea19..3b5e93eaf11 100644 --- a/crates/router/src/core/payouts/retry.rs +++ b/crates/router/src/core/payouts/retry.rs @@ -23,7 +23,7 @@ use crate::{ #[allow(clippy::too_many_arguments)] pub async fn do_gsm_multiple_connector_actions( state: &app::SessionState, - mut connectors: IntoIter<api::ConnectorData>, + mut connectors_routing_data: IntoIter<api::ConnectorRoutingData>, original_connector_data: api::ConnectorData, payout_data: &mut PayoutData, merchant_context: &domain::MerchantContext, @@ -53,13 +53,13 @@ pub async fn do_gsm_multiple_connector_actions( break; } - if connectors.len() == 0 { + if connectors_routing_data.len() == 0 { logger::info!("connectors exhausted for auto_retry payout"); metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]); break; } - connector = super::get_next_connector(&mut connectors)?; + connector = super::get_next_connector(&mut connectors_routing_data)?.connector_data; Box::pin(do_retry( &state.clone(), diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 39b601ed296..c65a8c6b9ec 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -8,7 +8,7 @@ use std::str::FromStr; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use std::sync::Arc; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[cfg(feature = "v1")] use api_models::open_router; use api_models::routing as routing_types; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] @@ -303,6 +303,56 @@ pub struct RoutingAlgorithmHelpers<'h> { pub routing_algorithm: &'h routing_types::RoutingAlgorithm, } +#[cfg(feature = "v1")] +pub enum RoutingDecisionData { + DebitRouting(DebitRoutingDecisionData), +} +#[cfg(feature = "v1")] +pub struct DebitRoutingDecisionData { + pub card_network: common_enums::enums::CardNetwork, + pub debit_routing_result: open_router::DebitRoutingOutput, +} +#[cfg(feature = "v1")] +impl RoutingDecisionData { + pub fn apply_routing_decision<F, D>(&self, payment_data: &mut D) + where + F: Send + Clone, + D: crate::core::payments::OperationSessionGetters<F> + + crate::core::payments::OperationSessionSetters<F> + + Send + + Sync + + Clone, + { + match self { + Self::DebitRouting(data) => data.apply_debit_routing_decision(payment_data), + } + } + + pub fn get_debit_routing_decision_data( + network: common_enums::enums::CardNetwork, + debit_routing_result: open_router::DebitRoutingOutput, + ) -> Self { + Self::DebitRouting(DebitRoutingDecisionData { + card_network: network, + debit_routing_result, + }) + } +} +#[cfg(feature = "v1")] +impl DebitRoutingDecisionData { + pub fn apply_debit_routing_decision<F, D>(&self, payment_data: &mut D) + where + F: Send + Clone, + D: crate::core::payments::OperationSessionGetters<F> + + crate::core::payments::OperationSessionSetters<F> + + Send + + Sync + + Clone, + { + payment_data.set_card_network(self.card_network.clone()); + payment_data.set_co_badged_card_data(&self.debit_routing_result); + } +} #[derive(Clone, Debug)] pub struct ConnectNameAndMCAIdForProfile<'a>( pub FxHashSet<( diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rs index e9088ded2e7..ebf521c4604 100644 --- a/crates/router/src/core/routing/transformers.rs +++ b/crates/router/src/core/routing/transformers.rs @@ -2,7 +2,7 @@ use api_models::routing::{ MerchantRoutingAlgorithm, RoutingAlgorithm as Algorithm, RoutingAlgorithmKind, RoutingDictionaryRecord, }; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[cfg(feature = "v1")] use api_models::{ open_router::{OpenRouterDecideGatewayRequest, PaymentInfo, RankingAlgorithm}, routing::RoutableConnectorChoice, @@ -12,8 +12,9 @@ use diesel_models::{ enums as storage_enums, routing_algorithm::{RoutingAlgorithm, RoutingProfileMetadata}, }; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[cfg(feature = "v1")] use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt; +use masking::{PeekInterface, Secret}; use crate::{ core::{errors, routing}, @@ -108,7 +109,7 @@ impl From<&routing::TransactionData<'_>> for storage_enums::TransactionType { } } -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[cfg(feature = "v1")] pub trait OpenRouterDecideGatewayRequestExt { fn construct_sr_request( attempt: &PaymentAttempt, @@ -118,9 +119,18 @@ pub trait OpenRouterDecideGatewayRequestExt { ) -> Self where Self: Sized; + + fn construct_debit_request( + attempt: &PaymentAttempt, + metadata: Option<String>, + card_isin: Option<Secret<String>>, + ranking_algorithm: Option<RankingAlgorithm>, + ) -> Self + where + Self: Sized; } -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[cfg(feature = "v1")] impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest { fn construct_sr_request( attempt: &PaymentAttempt, @@ -134,9 +144,10 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest { amount: attempt.net_amount.get_order_amount(), currency: attempt.currency.unwrap_or(storage_enums::Currency::USD), payment_type: "ORDER_PAYMENT".to_string(), - // payment_method_type: attempt.payment_method_type.clone().unwrap(), payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt payment_method: attempt.payment_method.unwrap_or_default(), + metadata: None, + card_isin: None, }, merchant_id: attempt.profile_id.clone(), eligible_gateway_list: Some( @@ -149,4 +160,29 @@ impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest { elimination_enabled: Some(is_elimination_enabled), } } + + fn construct_debit_request( + attempt: &PaymentAttempt, + metadata: Option<String>, + card_isin: Option<Secret<String>>, + ranking_algorithm: Option<RankingAlgorithm>, + ) -> Self { + Self { + payment_info: PaymentInfo { + payment_id: attempt.payment_id.clone(), + amount: attempt.net_amount.get_order_amount(), + currency: attempt.currency.unwrap_or(storage_enums::Currency::USD), + payment_type: "ORDER_PAYMENT".to_string(), + card_isin: card_isin.map(|value| value.peek().clone()), + metadata, + payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt + payment_method: attempt.payment_method.unwrap_or_default(), + }, + merchant_id: attempt.profile_id.clone(), + // eligible gateway list is not used in debit routing + eligible_gateway_list: None, + ranking_algorithm, + elimination_enabled: None, + } + } } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 9291bdb3bf0..5009b993710 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -92,8 +92,8 @@ use crate::{ }; #[derive(Clone)] pub enum ConnectorCallType { - PreDetermined(ConnectorData), - Retryable(Vec<ConnectorData>), + PreDetermined(ConnectorRoutingData), + Retryable(Vec<ConnectorRoutingData>), SessionMultiple(SessionConnectorDatas), #[cfg(feature = "v2")] Skip, @@ -122,6 +122,15 @@ pub struct ConnectorData { pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } +impl From<ConnectorData> for ConnectorRoutingData { + fn from(connector_data: ConnectorData) -> Self { + Self { + connector_data, + network: None, + } + } +} + #[derive(Clone, Debug)] pub struct SessionConnectorData { pub payment_method_sub_type: api_enums::PaymentMethodType, @@ -186,11 +195,15 @@ common_utils::create_list_wrapper!( ); pub fn convert_connector_data_to_routable_connectors( - connectors: &[ConnectorData], + connectors: &[ConnectorRoutingData], ) -> CustomResult<Vec<RoutableConnectorChoice>, common_utils::errors::ValidationError> { connectors .iter() - .map(|connector_data| RoutableConnectorChoice::foreign_try_from(connector_data.clone())) + .map(|connectors_routing_data| { + RoutableConnectorChoice::foreign_try_from( + connectors_routing_data.connector_data.clone(), + ) + }) .collect() } diff --git a/crates/router/src/types/api/fraud_check.rs b/crates/router/src/types/api/fraud_check.rs index 44dc3514669..b0ed7ed35d4 100644 --- a/crates/router/src/types/api/fraud_check.rs +++ b/crates/router/src/types/api/fraud_check.rs @@ -24,11 +24,17 @@ pub struct FraudCheckConnectorData { pub connector_name: enums::FrmConnectors, } pub enum ConnectorCallType { - PreDetermined(ConnectorData), - Retryable(Vec<ConnectorData>), + PreDetermined(ConnectorRoutingData), + Retryable(Vec<ConnectorRoutingData>), SessionMultiple(SessionConnectorDatas), } +#[derive(Clone)] +pub struct ConnectorRoutingData { + pub connector_data: ConnectorData, + pub network: Option<common_enums::CardNetwork>, +} + impl FraudCheckConnectorData { pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> { let connector_name = enums::FrmConnectors::from_str(name) diff --git a/crates/router/src/utils/verify_connector.rs b/crates/router/src/utils/verify_connector.rs index b13ba70e6fb..0f5d9e6b318 100644 --- a/crates/router/src/utils/verify_connector.rs +++ b/crates/router/src/utils/verify_connector.rs @@ -24,6 +24,7 @@ pub fn generate_card_from_details( card_issuing_country: None, bank_code: None, card_holder_name: None, + co_badged_card_data: None, }) } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 8b3372d7dec..3497a048a8a 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -52,6 +52,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { 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, @@ -302,6 +303,7 @@ async fn payments_create_failure() { 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( diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index c7ad3b69a32..d7017d3d44e 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -154,6 +154,7 @@ impl AdyenTest { 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, diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs index 0e538818d50..bf5a06f157a 100644 --- a/crates/router/tests/connectors/airwallex.rs +++ b/crates/router/tests/connectors/airwallex.rs @@ -83,6 +83,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { 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, }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), router_return_url: Some("https://google.com".to_string()), diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs index 78235278ed9..77ab8223145 100644 --- a/crates/router/tests/connectors/fiserv.rs +++ b/crates/router/tests/connectors/fiserv.rs @@ -54,6 +54,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { 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, }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs index ee6ac303e88..e173f4753d6 100644 --- a/crates/router/tests/connectors/rapyd.rs +++ b/crates/router/tests/connectors/rapyd.rs @@ -54,6 +54,7 @@ async fn should_only_authorize_payment() { 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, }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 @@ -82,6 +83,7 @@ async fn should_authorize_and_capture_payment() { 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, }), ..utils::PaymentAuthorizeType::default().0 }), diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index ede3aeb17db..d6925ae1667 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -941,6 +941,7 @@ impl Default for CCardType { 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, }) } } diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index 793a1cc15f4..22fd198bd0a 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -84,6 +84,7 @@ impl WorldlineTest { 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, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index f4f1eeb2fad..d682b5c3f8a 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -590,6 +590,12 @@ bank_redirect.trustly.connector_list = "adyen,aci" bank_redirect.open_banking_uk.connector_list = "adyen" bank_redirect.eps.connector_list = "globalpay,nexinets,aci" +[debit_routing_config] +supported_currencies = "USD" +supported_connectors = "adyen" + +[debit_routing_config.connector_supported_debit_networks] +adyen = "Star,Pulse,Accel,Nyce" [cors] max_age = 30
2025-04-25T13:45: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 --> A debit card can be linked to multiple card networks, with one serving as the primary (international) network and the others as secondary (local) networks. In debit routing, payments will be processed through the local network based on the merchant's requirements. This pr add the integration open router for debit routing. This pull request introduces a comprehensive set of changes to support debit routing functionality, expand card network capabilities, and improve code maintainability. Key updates include the addition of debit routing configurations, new card networks, and corresponding transformations across multiple modules. Below is a summary of the most important changes: ### Debit Routing Enhancements: * Added a new `DebitRoutingConfig` struct to the `Settings` configuration, which includes supported currencies, connectors, and debit networks * Added a `debit_routing` module under the `core` directory to support debit routing logic ### Card Network Expansion: * Added support for new card networks (`Star`, `Pulse`, `Accel`, `Nyce`) in the `CardNetwork` enum and implemented corresponding logic for global network checks ### API Model Updates: * Added new routing-related fields and structs such as `DebitRoutingOutput`, `CoBadgedCardRequest`, and `DebitRoutingRequestData` to support debit routing in the `OpenRouter` module ### 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 locally by creating dummy co-badged card bin dump -> Create a merchant account and business profile -> Enable debit routing and provide merchant business country for the business profile ``` curl --location 'http://localhost:8080/account/merchant_1745690754/business_profile/pro_OiJkBiFuCYbYAkCG9X02' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --data '{ "is_debit_routing_enabled": true, "merchant_business_country": "US" }' ``` -> Create a adyen connector account as we have debit routing flow only for adyen -> Make a payment with a co-badged card ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key: ' \ --data-raw '{ "amount": 100, "amount_to_capture": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "setup_future_usage": "on_session", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1745693422", "return_url": "http://127.0.0.1:4040", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4400002000000004", "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", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "payment_id": "pay_RjnzToNFSTe9QjbKcZUk", "merchant_id": "merchant_1745690754", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "adyen", "client_secret": "pay_RjnzToNFSTe9QjbKcZUk_secret_jpBstmZ1YgDBO0b0XStn", "created": "2025-04-26T18:50:32.942Z", "currency": "USD", "customer_id": "cu_1745693422", "customer": { "id": "cu_1745693422", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0004", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "440000", "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": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1745693422", "created_at": 1745693432, "expires": 1745697032, "secret": "epk_dbe0b04c709b4984a02f312e4c5ec36f" }, "manual_retry_allowed": false, "connector_transaction_id": "JRVPVXD3PD22KMV5", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_RjnzToNFSTe9QjbKcZUk_1", "payment_link": null, "profile_id": "pro_OiJkBiFuCYbYAkCG9X02", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_VyX6BwB09KJrmeR1ODFD", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-26T19:05:32.941Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-26T18:50:36.398Z", "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 } ``` -> logs indicating debit routing flow ![image](https://github.com/user-attachments/assets/28042da0-54d2-4af5-b6fe-0f758616acc6) -> connector request, card brand or network is being sent as `star` ![image](https://github.com/user-attachments/assets/ec378e88-4be3-474c-959c-236749b5f201) -> adyen dashboard indicating the payment was processed with star network ![image](https://github.com/user-attachments/assets/8a628ebe-a466-4a32-8312-93ffcc325fba) ## 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.114.0
34dd99d8050a84f0478cdb4fa0f0cc83608e52d9
34dd99d8050a84f0478cdb4fa0f0cc83608e52d9
juspay/hyperswitch
juspay__hyperswitch-7533
Bug: Add zero auth mandates support for nexixpay Zero auth mandates support for nexixpay.
diff --git a/crates/hyperswitch_connectors/src/connectors/adyen.rs b/crates/hyperswitch_connectors/src/connectors/adyen.rs index 8e0694336b5..b047d99a9d0 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen.rs @@ -72,10 +72,7 @@ use hyperswitch_interfaces::{ use masking::{ExposeInterface, Mask, Maskable, Secret}; use ring::hmac; use router_env::{instrument, tracing}; -use transformers::{ - self as adyen, convert_payment_authorize_router_response, - convert_setup_mandate_router_data_to_authorize_router_data, -}; +use transformers as adyen; #[cfg(feature = "payouts")] use crate::utils::PayoutsData as UtilsPayoutData; @@ -86,7 +83,11 @@ use crate::{ AcceptDisputeRouterData, DefendDisputeRouterData, ResponseRouterData, SubmitEvidenceRouterData, }, - utils::{self as connector_utils, is_mandate_supported, ForeignTryFrom, PaymentMethodDataType}, + utils::{ + self as connector_utils, convert_payment_authorize_router_response, + convert_setup_mandate_router_data_to_authorize_router_data, is_mandate_supported, + ForeignTryFrom, PaymentMethodDataType, + }, }; const ADYEN_API_VERSION: &str = "v68"; diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 793a33e1fc1..2e87967b0f9 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -1,5 +1,3 @@ -use std::marker::PhantomData; - #[cfg(feature = "payouts")] use api_models::payouts::{self, PayoutMethodData}; use api_models::{ @@ -27,16 +25,14 @@ use hyperswitch_domain_models::{ router_data::{ ConnectorAuthType, ErrorResponse, PaymentMethodBalance, PaymentMethodToken, RouterData, }, - router_request_types::{ - PaymentsAuthorizeData, PaymentsPreProcessingData, ResponseId, SubmitEvidenceRequestData, - }, + router_request_types::{PaymentsPreProcessingData, ResponseId, SubmitEvidenceRequestData}, router_response_types::{ AcceptDisputeResponse, DefendDisputeResponse, MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, SubmitEvidenceResponse, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, - PaymentsPreProcessingRouterData, RefundsRouterData, SetupMandateRouterData, + PaymentsPreProcessingRouterData, RefundsRouterData, }, }; #[cfg(feature = "payouts")] @@ -5545,106 +5541,3 @@ impl }) } } - -pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data( - data: &SetupMandateRouterData, -) -> PaymentsAuthorizeData { - PaymentsAuthorizeData { - currency: data.request.currency, - payment_method_data: data.request.payment_method_data.clone(), - confirm: data.request.confirm, - statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(), - mandate_id: data.request.mandate_id.clone(), - setup_future_usage: data.request.setup_future_usage, - off_session: data.request.off_session, - setup_mandate_details: data.request.setup_mandate_details.clone(), - router_return_url: data.request.router_return_url.clone(), - email: data.request.email.clone(), - customer_name: data.request.customer_name.clone(), - amount: 0, - order_tax_amount: Some(MinorUnit::zero()), - minor_amount: MinorUnit::new(0), - statement_descriptor: None, - capture_method: None, - webhook_url: None, - complete_authorize_url: None, - browser_info: data.request.browser_info.clone(), - order_details: None, - order_category: None, - session_token: None, - enrolled_for_3ds: true, - related_transaction_id: None, - payment_experience: None, - payment_method_type: None, - customer_id: None, - surcharge_details: None, - request_incremental_authorization: data.request.request_incremental_authorization, - metadata: None, - authentication_data: None, - customer_acceptance: data.request.customer_acceptance.clone(), - split_payments: None, // TODO: allow charges on mandates? - merchant_order_reference_id: None, - integrity_object: None, - additional_payment_method_data: None, - shipping_cost: data.request.shipping_cost, - merchant_account_id: None, - merchant_config_currency: None, - } -} - -pub(crate) fn convert_payment_authorize_router_response<F1, F2, T1, T2>( - item: (&RouterData<F1, T1, PaymentsResponseData>, T2), -) -> RouterData<F2, T2, PaymentsResponseData> { - let data = item.0; - let request = item.1; - RouterData { - flow: PhantomData, - request, - merchant_id: data.merchant_id.clone(), - connector: data.connector.clone(), - attempt_id: data.attempt_id.clone(), - tenant_id: data.tenant_id.clone(), - status: data.status, - payment_method: data.payment_method, - connector_auth_type: data.connector_auth_type.clone(), - description: data.description.clone(), - address: data.address.clone(), - auth_type: data.auth_type, - connector_meta_data: data.connector_meta_data.clone(), - connector_wallets_details: data.connector_wallets_details.clone(), - amount_captured: data.amount_captured, - minor_amount_captured: data.minor_amount_captured, - access_token: data.access_token.clone(), - response: data.response.clone(), - payment_id: data.payment_id.clone(), - session_token: data.session_token.clone(), - reference_id: data.reference_id.clone(), - customer_id: data.customer_id.clone(), - payment_method_token: None, - preprocessing_id: None, - connector_customer: data.connector_customer.clone(), - recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(), - connector_request_reference_id: data.connector_request_reference_id.clone(), - #[cfg(feature = "payouts")] - payout_method_data: data.payout_method_data.clone(), - #[cfg(feature = "payouts")] - quote_id: data.quote_id.clone(), - test_mode: data.test_mode, - payment_method_status: None, - payment_method_balance: data.payment_method_balance.clone(), - connector_api_version: data.connector_api_version.clone(), - connector_http_status_code: data.connector_http_status_code, - external_latency: data.external_latency, - apple_pay_flow: data.apple_pay_flow.clone(), - frm_metadata: data.frm_metadata.clone(), - dispute_id: data.dispute_id.clone(), - refund_id: data.refund_id.clone(), - connector_response: data.connector_response.clone(), - integrity_check: Ok(()), - additional_merchant_data: data.additional_merchant_data.clone(), - header_payload: data.header_payload.clone(), - connector_mandate_request_reference_id: data.connector_mandate_request_reference_id.clone(), - authentication_id: data.authentication_id.clone(), - psd2_sca_exemption_type: data.psd2_sca_exemption_type, - } -} diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs index 264bca6b5a9..bed54d66e4d 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay.rs @@ -32,7 +32,7 @@ use hyperswitch_domain_models::{ types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, - PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, }, }; use hyperswitch_interfaces::{ @@ -228,6 +228,91 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nexixpay { + fn get_headers( + &self, + req: &SetupMandateRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &SetupMandateRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/orders/3steps/init", self.base_url(connectors))) + } + + fn get_request_body( + &self, + req: &SetupMandateRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let authorize_req = utils::convert_payment_authorize_router_response(( + req, + utils::convert_setup_mandate_router_data_to_authorize_router_data(req), + )); + + let amount = utils::convert_amount( + self.amount_converter, + authorize_req.request.minor_amount, + authorize_req.request.currency, + )?; + + let connector_router_data = nexixpay::NexixpayRouterData::from((amount, &authorize_req)); + let connector_req = nexixpay::NexixpayPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &SetupMandateRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::SetupMandateType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::SetupMandateType::get_headers(self, req, connectors)?) + .set_body(types::SetupMandateType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &SetupMandateRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> { + let response: nexixpay::PaymentsResponse = res + .response + .parse_struct("PaymentsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs index 27eebf78dfb..06925eea6cf 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs @@ -9,10 +9,13 @@ use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, RouterData}, - router_flow_types::refunds::{Execute, RSync}, + router_flow_types::{ + refunds::{Execute, RSync}, + SetupMandate, + }, router_request_types::{ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, - PaymentsPreProcessingData, PaymentsSyncData, ResponseId, + PaymentsPreProcessingData, PaymentsSyncData, ResponseId, SetupMandateRequestData, }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, @@ -31,7 +34,8 @@ use crate::{ utils::{ get_unimplemented_payment_method_error_message, to_connector_meta, to_connector_meta_from_secret, CardData, PaymentsAuthorizeRequestData, - PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, RouterData as _, + PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, + PaymentsSetupMandateRequestData, RouterData as _, }, }; @@ -1290,3 +1294,74 @@ impl<F> }) } } + +impl + TryFrom< + ResponseRouterData< + SetupMandate, + PaymentsResponse, + SetupMandateRequestData, + PaymentsResponseData, + >, + > for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + SetupMandate, + PaymentsResponse, + SetupMandateRequestData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let complete_authorize_url = item.data.request.get_complete_authorize_url()?; + let operation_id: String = item.response.operation.operation_id.clone(); + let redirection_form = nexixpay_threeds_link(NexixpayRedirectionRequest { + three_d_s_auth_url: item + .response + .three_d_s_auth_url + .clone() + .expose() + .to_string(), + three_ds_request: item.response.three_d_s_auth_request.clone(), + return_url: complete_authorize_url.clone(), + transaction_id: operation_id.clone(), + })?; + let is_auto_capture = item.data.request.is_auto_capture()?; + let connector_metadata = Some(serde_json::json!(NexixpayConnectorMetaData { + three_d_s_auth_result: None, + three_d_s_auth_response: None, + authorization_operation_id: Some(operation_id.clone()), + cancel_operation_id: None, + capture_operation_id: { + if is_auto_capture { + Some(operation_id) + } else { + None + } + }, + psync_flow: NexixpayPaymentIntent::Authorize + })); + Ok(Self { + status: AttemptStatus::from(item.response.operation.operation_result.clone()), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.operation.order_id.clone(), + ), + redirection_data: Box::new(Some(redirection_form.clone())), + mandate_reference: Box::new(Some(MandateReference { + connector_mandate_id: item.data.connector_mandate_request_reference_id.clone(), + payment_method_id: None, + mandate_metadata: None, + connector_mandate_request_reference_id: None, + })), + connector_metadata, + network_txn_id: None, + connector_response_reference_id: Some(item.response.operation.order_id.clone()), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } +} diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index a34699498b5..b1bd7a04d5f 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -1,5 +1,6 @@ use std::{ collections::{HashMap, HashSet}, + marker::PhantomData, str::FromStr, }; @@ -44,6 +45,7 @@ use hyperswitch_domain_models::{ payment_method_data::{self, Card, CardDetailsForNetworkTransactionId, PaymentMethodData}, router_data::{ ApplePayPredecryptData, ErrorResponse, PaymentMethodToken, RecurringMandatePaymentData, + RouterData as ConnectorRouterData, }, router_request_types::{ AuthenticationData, BrowserInformation, CompleteAuthorizeData, ConnectorCustomerData, @@ -52,8 +54,8 @@ use hyperswitch_domain_models::{ PaymentsPreProcessingData, PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData, }, - router_response_types::CaptureSyncResponse, - types::OrderDetailsWithAmount, + router_response_types::{CaptureSyncResponse, PaymentsResponseData}, + types::{OrderDetailsWithAmount, SetupMandateRouterData}, }; use hyperswitch_interfaces::{api, consts, errors, types::Response}; use image::{DynamicImage, ImageBuffer, ImageFormat, Luma, Rgba}; @@ -2014,6 +2016,8 @@ pub trait PaymentsSetupMandateRequestData { fn get_return_url(&self) -> Result<String, Error>; fn get_webhook_url(&self) -> Result<String, Error>; fn get_optional_language_from_browser_info(&self) -> Option<String>; + fn get_complete_authorize_url(&self) -> Result<String, Error>; + fn is_auto_capture(&self) -> Result<bool, Error>; } impl PaymentsSetupMandateRequestData for SetupMandateRequestData { @@ -2048,6 +2052,20 @@ impl PaymentsSetupMandateRequestData for SetupMandateRequestData { .clone() .and_then(|browser_info| browser_info.language) } + fn get_complete_authorize_url(&self) -> Result<String, Error> { + self.complete_authorize_url + .clone() + .ok_or_else(missing_field_err("complete_authorize_url")) + } + fn is_auto_capture(&self) -> Result<bool, Error> { + match self.capture_method { + Some(enums::CaptureMethod::Automatic) + | Some(enums::CaptureMethod::SequentialAutomatic) + | None => Ok(true), + Some(enums::CaptureMethod::Manual) => Ok(false), + Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), + } + } } pub trait PaymentMethodTokenizationRequestData { @@ -5855,3 +5873,106 @@ where let output = <&str>::deserialize(v)?; output.to_uppercase().parse::<T>().map_err(D::Error::custom) } + +pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data( + data: &SetupMandateRouterData, +) -> PaymentsAuthorizeData { + PaymentsAuthorizeData { + currency: data.request.currency, + payment_method_data: data.request.payment_method_data.clone(), + confirm: data.request.confirm, + statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(), + mandate_id: data.request.mandate_id.clone(), + setup_future_usage: data.request.setup_future_usage, + off_session: data.request.off_session, + setup_mandate_details: data.request.setup_mandate_details.clone(), + router_return_url: data.request.router_return_url.clone(), + email: data.request.email.clone(), + customer_name: data.request.customer_name.clone(), + amount: 0, + order_tax_amount: Some(MinorUnit::zero()), + minor_amount: MinorUnit::new(0), + statement_descriptor: None, + capture_method: None, + webhook_url: None, + complete_authorize_url: None, + browser_info: data.request.browser_info.clone(), + order_details: None, + order_category: None, + session_token: None, + enrolled_for_3ds: true, + related_transaction_id: None, + payment_experience: None, + payment_method_type: None, + customer_id: None, + surcharge_details: None, + request_incremental_authorization: data.request.request_incremental_authorization, + metadata: None, + authentication_data: None, + customer_acceptance: data.request.customer_acceptance.clone(), + split_payments: None, // TODO: allow charges on mandates? + merchant_order_reference_id: None, + integrity_object: None, + additional_payment_method_data: None, + shipping_cost: data.request.shipping_cost, + merchant_account_id: None, + merchant_config_currency: None, + } +} + +pub(crate) fn convert_payment_authorize_router_response<F1, F2, T1, T2>( + item: (&ConnectorRouterData<F1, T1, PaymentsResponseData>, T2), +) -> ConnectorRouterData<F2, T2, PaymentsResponseData> { + let data = item.0; + let request = item.1; + ConnectorRouterData { + flow: PhantomData, + request, + merchant_id: data.merchant_id.clone(), + connector: data.connector.clone(), + attempt_id: data.attempt_id.clone(), + tenant_id: data.tenant_id.clone(), + status: data.status, + payment_method: data.payment_method, + connector_auth_type: data.connector_auth_type.clone(), + description: data.description.clone(), + address: data.address.clone(), + auth_type: data.auth_type, + connector_meta_data: data.connector_meta_data.clone(), + connector_wallets_details: data.connector_wallets_details.clone(), + amount_captured: data.amount_captured, + minor_amount_captured: data.minor_amount_captured, + access_token: data.access_token.clone(), + response: data.response.clone(), + payment_id: data.payment_id.clone(), + session_token: data.session_token.clone(), + reference_id: data.reference_id.clone(), + customer_id: data.customer_id.clone(), + payment_method_token: None, + preprocessing_id: None, + connector_customer: data.connector_customer.clone(), + recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(), + connector_request_reference_id: data.connector_request_reference_id.clone(), + #[cfg(feature = "payouts")] + payout_method_data: data.payout_method_data.clone(), + #[cfg(feature = "payouts")] + quote_id: data.quote_id.clone(), + test_mode: data.test_mode, + payment_method_status: None, + payment_method_balance: data.payment_method_balance.clone(), + connector_api_version: data.connector_api_version.clone(), + connector_http_status_code: data.connector_http_status_code, + external_latency: data.external_latency, + apple_pay_flow: data.apple_pay_flow.clone(), + frm_metadata: data.frm_metadata.clone(), + dispute_id: data.dispute_id.clone(), + refund_id: data.refund_id.clone(), + connector_response: data.connector_response.clone(), + integrity_check: Ok(()), + additional_merchant_data: data.additional_merchant_data.clone(), + header_payload: data.header_payload.clone(), + connector_mandate_request_reference_id: data.connector_mandate_request_reference_id.clone(), + authentication_id: data.authentication_id.clone(), + psd2_sca_exemption_type: data.psd2_sca_exemption_type, + } +} diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index ff5534dcebc..4671c4552f0 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -918,6 +918,8 @@ pub struct SetupMandateRequestData { pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub request_incremental_authorization: bool, pub metadata: Option<pii::SecretSerdeValue>, + pub complete_authorize_url: Option<String>, + pub capture_method: Option<storage_enums::CaptureMethod>, // MinorUnit for amount framework pub minor_amount: Option<MinorUnit>, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 804516b86a4..f50e28e940a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -958,6 +958,8 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( metadata: payment_data.payment_intent.metadata, minor_amount: Some(payment_data.payment_attempt.amount_details.get_net_amount()), shipping_cost: payment_data.payment_intent.amount_details.shipping_cost, + capture_method: Some(payment_data.payment_intent.capture_method), + complete_authorize_url, }; let connector_mandate_request_reference_id = payment_data .payment_attempt @@ -4001,6 +4003,12 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ &attempt.merchant_id, merchant_connector_account_id_or_connector_name, )); + let complete_authorize_url = Some(helpers::create_complete_authorize_url( + router_base_url, + attempt, + connector_name, + payment_data.creds_identifier.as_deref(), + )); Ok(Self { currency: payment_data.currency, @@ -4032,6 +4040,8 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ metadata: payment_data.payment_intent.metadata.clone().map(Into::into), shipping_cost: payment_data.payment_intent.shipping_cost, webhook_url, + complete_authorize_url, + capture_method: payment_data.payment_attempt.capture_method, }) } }
2025-03-17T09:06:38Z
## 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 zero auth mandate flow for nexixpay connector. It uses 3ds payments flow to create mandates. ### 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). --> We have to add support for zero amount CIT payments for nexixpay so that merchants can do MIT payments with required value. ## 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: <img width="1728" alt="image" src="https://github.com/user-attachments/assets/63853683-40cd-409c-a3e7-00c1b0ffc0e0" /> Below curls should be used for testing zero auth mandates: 1. Payments CIT ``` curl --location 'localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_PczXRK73enU0k1JDyjEZ8u76iSUxrocg963jiEzfbY7z1ncgosfLvQFlRoHOcux4' \ --data-raw '{ "amount": 0, "currency": "EUR", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://abc.com", "email": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "setup_future_usage": "off_session" }' ``` 2. Confirm CIT ``` curl --location 'http://localhost:8080/payments/pay_I46gW94NSY7cGwi0BTjl/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_PczXRK73enU0k1JDyjEZ8u76iSUxrocg963jiEzfbY7z1ncgosfLvQFlRoHOcux4' \ --data-raw '{ "confirm": true, "customer_id": "customer123", "payment_type": "setup_mandate", "customer_acceptance": { "acceptance_type": "online", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } }, "payment_method": "card", "payment_method_type": "credit", "email": "[email protected]", "payment_method_data": { "card": { "card_number": "4349940199004549", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "396" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IT", "first_name": "joseph", "last_name": "Doe" }, "email": "[email protected]", "phone": { "number": "8056594427", "country_code": "+91" } } } }' ``` 3. MIT payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_PczXRK73enU0k1JDyjEZ8u76iSUxrocg963jiEzfbY7z1ncgosfLvQFlRoHOcux4' \ --data '{ "amount": 3545, "currency": "EUR", "confirm": true, "customer_id": "customer123", "recurring_details": { "type": "payment_method_id", "data": "pm_unSAF4FSldeu1wAeLvpe" }, "off_session": true }' ``` ## 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.113.0
a87471c45dee50e7b9c9674aa8c9bb668c892917
a87471c45dee50e7b9c9674aa8c9bb668c892917
juspay/hyperswitch
juspay__hyperswitch-7534
Bug: feat(analytics): add issuer as filter for authentication analytics Add `acs_reference_number` as filter for authentication analytics.
diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index bdcbdd86a94..4d11f19d531 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -169,6 +169,7 @@ pub async fn get_filters( AuthEventDimensions::ErrorMessage => fil.error_message, AuthEventDimensions::AuthenticationConnector => fil.authentication_connector.map(|i| i.as_ref().to_string()), AuthEventDimensions::MessageVersion => fil.message_version, + AuthEventDimensions::AcsReferenceNumber => fil.acs_reference_number, }) .collect::<Vec<String>>(); res.query_data.push(AuthEventFilterValue { diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs index 5f65eeaa279..1961116b84c 100644 --- a/crates/analytics/src/auth_events/filters.rs +++ b/crates/analytics/src/auth_events/filters.rs @@ -59,4 +59,5 @@ pub struct AuthEventFilterRow { pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>>, pub message_version: Option<String>, + pub acs_reference_number: Option<String>, } diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index a3d0fe7b683..6315c1338ee 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -45,6 +45,7 @@ pub struct AuthEventMetricRow { pub error_message: Option<String>, pub authentication_connector: Option<DBEnumWrapper<storage_enums::AuthenticationConnectors>>, pub message_version: Option<String>, + pub acs_reference_number: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub start_bucket: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index b82d1ef4c35..fbdc4b75b3e 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -110,6 +110,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs index 682e8a07f6b..b4c0a5c5957 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -100,6 +100,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs index 047511d477c..b064cb7ab30 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs @@ -119,6 +119,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs index 9342e9047e0..3a122fd42a9 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs @@ -111,6 +111,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 984350efe6b..37435123623 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -105,6 +105,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index 5a2a9400b20..0265fc7e457 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -115,6 +115,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 279844388f2..178dcba20bf 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -107,6 +107,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index 91e8cc54289..b78f84326de 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -112,6 +112,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index b08edb10113..d114e36f140 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -108,6 +108,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index 80417ac64bf..a56d5b660aa 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -112,6 +112,7 @@ where i.error_message.clone(), i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), + i.acs_reference_number.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/types.rs b/crates/analytics/src/auth_events/types.rs index ac7ee2462ee..863e50a0af2 100644 --- a/crates/analytics/src/auth_events/types.rs +++ b/crates/analytics/src/auth_events/types.rs @@ -53,6 +53,15 @@ where ) .attach_printable("Error adding message version filter")?; } + + if !self.acs_reference_number.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::AcsReferenceNumber, + &self.acs_reference_number, + ) + .attach_printable("Error adding acs reference number filter")?; + } Ok(()) } } diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 6a6237e6783..5a2f097bb0d 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -231,6 +231,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let acs_reference_number: Option<String> = + row.try_get("acs_reference_number").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -249,6 +254,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow error_message, authentication_connector, message_version, + acs_reference_number, count, start_bucket, end_bucket, @@ -288,6 +294,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let acs_reference_number: Option<String> = + row.try_get("acs_reference_number").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; Ok(Self { authentication_status, trans_status, @@ -295,6 +306,7 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow error_message, authentication_connector, message_version, + acs_reference_number, }) } } diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index a0ddead1363..0832788e261 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -51,6 +51,7 @@ pub fn get_auth_event_dimensions() -> Vec<NameDescription> { vec![ AuthEventDimensions::AuthenticationConnector, AuthEventDimensions::MessageVersion, + AuthEventDimensions::AcsReferenceNumber, ] .into_iter() .map(Into::into) diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 2360e564642..8a1c168aa2f 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -23,6 +23,8 @@ pub struct AuthEventFilters { pub authentication_connector: Vec<AuthenticationConnectors>, #[serde(default)] pub message_version: Vec<String>, + #[serde(default)] + pub acs_reference_number: Vec<String>, } #[derive( @@ -50,6 +52,7 @@ pub enum AuthEventDimensions { ErrorMessage, AuthenticationConnector, MessageVersion, + AcsReferenceNumber, } #[derive( @@ -135,6 +138,7 @@ pub struct AuthEventMetricsBucketIdentifier { pub error_message: Option<String>, pub authentication_connector: Option<AuthenticationConnectors>, pub message_version: Option<String>, + pub acs_reference_number: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] @@ -151,6 +155,7 @@ impl AuthEventMetricsBucketIdentifier { error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, + acs_reference_number: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { @@ -160,6 +165,7 @@ impl AuthEventMetricsBucketIdentifier { error_message, authentication_connector, message_version, + acs_reference_number, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } @@ -173,6 +179,7 @@ impl Hash for AuthEventMetricsBucketIdentifier { self.authentication_type.hash(state); self.authentication_connector.hash(state); self.message_version.hash(state); + self.acs_reference_number.hash(state); self.error_message.hash(state); self.time_bucket.hash(state); }
2025-03-17T11:39:35Z
## 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 --> Added `acs_reference_number` as filter for authentication analytics. Will display it as `issuer` on FE dashboard. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Better insights into authentication data by applying filters ## 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)? --> Get Info curl: ```bash curl --location 'http://localhost:8080/analytics/v1/auth_events/info' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Referer: http://localhost:9000/dashboard/analytics-payments' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-origin' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36' \ --header 'X-Merchant-Id: merchant_1740414909' \ --header 'X-Profile-Id: pro_q9g6emqpc7b41Lo7UXpx' \ --header 'api-key: dev_zKT6VT7TvcxCtwq8N716HELM6HZJAwZvkWVHrlKAU54Pzu6D18GL3u3UswnkMkug' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWFiNWIxNDEtNjQwOC00YTUyLTk2MjMtNTVhNTgxMTU1M2U4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQwNDE0OTA5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MTI3NDY4NSwib3JnX2lkIjoib3JnX1QwSEtYNHYyRGFRT2lHUDVwRk52IiwicHJvZmlsZV9pZCI6InByb19xOWc2ZW1xcGM3YjQxTG83VVhweCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.LIExs1jjG6N5AFu5_S3oiuy77fWF0IbJmNGbK8HHLXI' \ --header 'sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' ``` Sample Output: ```json { "metrics": [ { "name": "authentication_count", "desc": "" }, { "name": "authentication_attempt_count", "desc": "" }, { "name": "authentication_success_count", "desc": "" }, { "name": "challenge_flow_count", "desc": "" }, { "name": "frictionless_flow_count", "desc": "" }, { "name": "frictionless_success_count", "desc": "" }, { "name": "challenge_attempt_count", "desc": "" }, { "name": "challenge_success_count", "desc": "" }, { "name": "authentication_error_message", "desc": "" }, { "name": "authentication_funnel", "desc": "" } ], "downloadDimensions": null, "dimensions": [ { "name": "authentication_connector", "desc": "" }, { "name": "message_version", "desc": "" }, { "name": "acs_reference_number", "desc": "" } ] } ``` acs_reference_number is being sent in the dimensions list. Filters API: ```bash curl --location 'http://localhost:8080/analytics/v1/filters/auth_events' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: hyperswitch' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiM2RlMDFhYWYtOWVkMi00YTY5LTg3YWItNWU1YmI2ZWFiNGQ5IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQyMjEyMzQxIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0MjM4NTE0Miwib3JnX2lkIjoib3JnX3pMQmRNTnpLaDZrNmhiT2tockdJIiwicHJvZmlsZV9pZCI6InByb19LWnhHZ21rUHFkMldQdXBFa2psWCIsInRlbmFudF9pZCI6InB1YmxpYyJ9.efMstkbz90nfMKju4PmdIedl_tN-FHW3aQKD44jOnxo' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '{ "timeRange": { "startTime": "2025-02-01T18:30:00.000Z", "endTime": "2025-02-28T09:22:30.000Z" }, "groupByNames": [ "message_version", "authentication_connector", "acs_reference_number" ], "source": "BATCH", "delta": true }' ``` Sample Output: ```json { "queryData": [ { "dimension": "message_version", "values": [ "2.3.1" ] }, { "dimension": "authentication_connector", "values": [ "netcetera" ] }, { "dimension": "acs_reference_number", "values": [ "3DS_LOA_ACS_201_13579" ] } ] } ``` ## 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.113.0
2d17dad25d0966fc95f17e0ee91598ea445d4dc9
2d17dad25d0966fc95f17e0ee91598ea445d4dc9
juspay/hyperswitch
juspay__hyperswitch-7529
Bug: [FEATURE] emit payment status before rendering the UI ### Feature Description Payment link to emit the latest payment intent status before mounting the SDK and rendering UI. Usecase - this can be used by merchants who embed these links as an iframe to take decision based on the latest intent status. ### Possible Implementation Before mounting SDK or rendering the UI, emit an event via `postMessage` which can be listened on by the parent window. Message format ``` { "payment": { "status": "IntentStatus" } } ``` ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 27d7b82e547..840d4274709 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -7944,6 +7944,7 @@ pub struct PaymentLinkDetails { pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index c13e087947b..48004dd740b 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -191,7 +191,7 @@ pub async fn form_payment_link_data( let merchant_name = capitalize_first_char(&payment_link_config.seller_name); let payment_link_status = check_payment_link_status(session_expiry); - let is_terminal_state = check_payment_link_invalid_conditions( + let is_payment_link_terminal_state = check_payment_link_invalid_conditions( payment_intent.status, &[ storage_enums::IntentStatus::Cancelled, @@ -201,9 +201,11 @@ pub async fn form_payment_link_data( storage_enums::IntentStatus::RequiresMerchantAction, storage_enums::IntentStatus::Succeeded, storage_enums::IntentStatus::PartiallyCaptured, + storage_enums::IntentStatus::RequiresCustomerAction, ], ); - if is_terminal_state || payment_link_status == api_models::payments::PaymentLinkStatus::Expired + if is_payment_link_terminal_state + || payment_link_status == api_models::payments::PaymentLinkStatus::Expired { let status = match payment_link_status { api_models::payments::PaymentLinkStatus::Active => { @@ -211,7 +213,7 @@ pub async fn form_payment_link_data( PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } api_models::payments::PaymentLinkStatus::Expired => { - if is_terminal_state { + if is_payment_link_terminal_state { logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status); PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } else { @@ -292,6 +294,7 @@ pub async fn form_payment_link_data( payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(), sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(), payment_link_ui_rules: payment_link_config.payment_link_ui_rules.clone(), + status: payment_intent.status, enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready, }; diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js index e73e23076a9..5c6f3a6b373 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js @@ -181,6 +181,30 @@ var hyper = null; const translations = getTranslations(window.__PAYMENT_DETAILS.locale); +var isFramed = false; +try { + isFramed = window.parent.location !== window.location; + + // If parent's window object is restricted, DOMException is + // thrown which concludes that the webpage is iframed +} catch (err) { + isFramed = true; +} + +/** + * Trigger - on boot + * Use - emit latest payment status to parent window + */ +function emitPaymentStatus(paymentDetails) { + var message = { + payment: { + status: paymentDetails.status, + } + }; + + window.parent.postMessage(message, "*"); +} + /** * Trigger - init function invoked once the script tag is loaded * Use @@ -190,13 +214,16 @@ const translations = getTranslations(window.__PAYMENT_DETAILS.locale); * - Initialize event listeners for updating UI on screen size changes * - Initialize SDK **/ - - function boot() { // @ts-ignore var paymentDetails = window.__PAYMENT_DETAILS; + // Emit latest payment status + if (isFramed) { + emitPaymentStatus(paymentDetails); + } + if (paymentDetails.display_sdk_only) { hide(".checkout-page") var sdkDisplayWidth = document.querySelector('.hyper-checkout-sdk'); diff --git a/crates/router/src/core/payment_link/payment_link_status/status.css b/crates/router/src/core/payment_link/payment_link_status/status.css index 113f1353138..65b7b11d956 100644 --- a/crates/router/src/core/payment_link/payment_link_status/status.css +++ b/crates/router/src/core/payment_link/payment_link_status/status.css @@ -137,6 +137,10 @@ body > div { font-size: 13px; } +.hidden { + display: none; +} + .ellipsis-container-2 { height: 2.5em; overflow: hidden; diff --git a/crates/router/src/core/payment_link/payment_link_status/status.html b/crates/router/src/core/payment_link/payment_link_status/status.html index c78a0bb556d..7531c8df444 100644 --- a/crates/router/src/core/payment_link/payment_link_status/status.html +++ b/crates/router/src/core/payment_link/payment_link_status/status.html @@ -16,7 +16,7 @@ {{ rendered_js }} </script> </head> - <body onload="boot()"> + <body onload="boot()" class="hidden"> <div> <div class="hyper-checkout-status-wrap"> <div id="hyper-checkout-status-header"></div> diff --git a/crates/router/src/core/payment_link/payment_link_status/status.js b/crates/router/src/core/payment_link/payment_link_status/status.js index 8c9697fd53e..16949d546a6 100644 --- a/crates/router/src/core/payment_link/payment_link_status/status.js +++ b/crates/router/src/core/payment_link/payment_link_status/status.js @@ -52,8 +52,8 @@ function invertToBW(color, bw, asArr) { ? hexToRgbArray(options.black) : options.black : asArr - ? hexToRgbArray(options.white) - : options.white; + ? hexToRgbArray(options.white) + : options.white; } function invert(color, bw) { if (bw === void 0) { @@ -87,6 +87,31 @@ window.state = { }; const translations = getTranslations(window.__PAYMENT_DETAILS.locale); + +var isFramed = false; +try { + isFramed = window.parent.location !== window.location; + + // If parent's window object is restricted, DOMException is + // thrown which concludes that the webpage is iframed +} catch (err) { + isFramed = true; +} + +/** + * Trigger - on boot + * Use - emit latest payment status to parent window + */ +function emitPaymentStatus(paymentDetails) { + var message = { + payment: { + status: paymentDetails.status, + } + }; + + window.parent.postMessage(message, "*"); +} + /** * Trigger - init function invoked once the script tag is loaded * Use @@ -100,20 +125,43 @@ function boot() { // @ts-ignore var paymentDetails = window.__PAYMENT_DETAILS; - // Attach document icon - if (paymentDetails.merchant_logo) { - var link = document.createElement("link"); - link.rel = "icon"; - link.href = paymentDetails.merchant_logo; - link.type = "image/x-icon"; - document.head.appendChild(link); + // Emit latest payment status + if (isFramed) { + emitPaymentStatus(paymentDetails); } - // Render status details - renderStatusDetails(paymentDetails); + if (shouldRenderUI(paymentDetails)) { + removeClass("body", "hidden"); + // Attach document icon + if (paymentDetails.merchant_logo) { + var link = document.createElement("link"); + link.rel = "icon"; + link.href = paymentDetails.merchant_logo; + link.type = "image/x-icon"; + document.head.appendChild(link); + } + + // Render status details + renderStatusDetails(paymentDetails); - // Add event listeners - initializeEventListeners(paymentDetails); + // Add event listeners + initializeEventListeners(paymentDetails); + } +} + +/** + * Trigger - on boot + * Use - Check if UI should be rendered based on some conditions + * @returns {Boolean} + */ +function shouldRenderUI(paymentDetails) { + var status = paymentDetails.status; + if (isFramed) { + switch (status) { + case "requires_customer_action": return false; + } + } + return true; } /** @@ -158,6 +206,7 @@ function renderStatusDetails(paymentDetails) { ).toTimeString(); break; + case "requires_customer_action": case "processing": statusDetails.imageSource = "https://live.hyperswitch.io/payment-link-assets/pending.png"; statusDetails.message = translations.paymentTakingLonger; @@ -279,7 +328,7 @@ function renderStatusDetails(paymentDetails) { var innerText = secondsLeft === 0 ? translations.redirecting - : translations.redirectingIn + secondsLeft + " "+translations.seconds; + : translations.redirectingIn + secondsLeft + " " + translations.seconds; // @ts-ignore statusRedirectTextNode.innerText = innerText; if (secondsLeft === 0) { @@ -341,5 +390,18 @@ function initializeEventListeners(paymentDetails) { if (statusRedirectTextNode instanceof HTMLDivElement) { statusRedirectTextNode.style.color = contrastBWColor; } - }; +}; +function addClass(id, className) { + var element = document.querySelector(id); + if (element instanceof HTMLElement) { + element.classList.add(className); + } +} + +function removeClass(id, className) { + var element = document.querySelector(id); + if (element instanceof HTMLElement) { + element.classList.remove(className); + } +} \ No newline at end of file
2025-03-17T08:03:13Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR adds functionality for payment links to - emit latest payment intent status before rendering status UI or payment widget - consider `requires_customer_action` as payment link's terminal state ### 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 Helps merchants take action for `requires_customer_action` state in case user re-renders the link for the mentioned intent status. ## How did you test it? Tested locally using an iframe. <details> <summary>1. Use below template for payment links</summary> ``` <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> --> <title>Document</title> <style> html, body { margin: 0; display: flex; align-items: center; justify-content: center; background-color: bisque; height: 100vh; width: 100vw; } iframe { border-radius: 4px; height: 90vh; width: 90vw; background-color: white; } </style> </head> <body> <iframe src="http://localhost:8080/payment_link/merchant_1742192403/pay_1aHs36MZD0zffE4bO538?locale=en" frameborder="0"></iframe> </body> <script> window.addEventListener("message", function(event) { if (event.origin === "http://localhost:8080") { var status = event.data.payment.status; switch (status) { case "expired": case "requires_customer_action": { window.location.href = "https://google.com"; } } } }); </script> </html> ``` </details> <details> <summary>2. Create a payment link</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_4AE12pRff5kcWKXt1Dn3CfMCHOtgfXPyAO92s8kWae1xALFonMSs2hzpAGZ1ov6Q' \ --data-raw '{"customer_id":"cus_ALQFPJO2ZOSIg4XOUIZo","profile_id":"pro_qukvQ1whBBb6pdKnzvvN","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":100,"currency":"USD","payment_link":true,"capture_method":"automatic","email":"[email protected]","session_expiry":100000,"return_url":"https://example.com","payment_link_config_id":"style1"}' Response {"payment_id":"pay_yzSbFQNh8oJoa6cSkxQM","merchant_id":"merchant_1742192403","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_yzSbFQNh8oJoa6cSkxQM_secret_tPrHESV8PXuLApSxMxZj","created":"2025-03-17T08:06:06.305Z","currency":"USD","customer_id":"cus_ALQFPJO2ZOSIg4XOUIZo","customer":{"id":"cus_ALQFPJO2ZOSIg4XOUIZo","name":"John Nether","email":"[email protected]","phone":"6168205362","phone_country_code":"+1"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Nether","phone":"6168205362","return_url":"https://example.com/","authentication_type":null,"statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_ALQFPJO2ZOSIg4XOUIZo","created_at":1742198766,"expires":1742202366,"secret":"epk_db9da1a985644cd08c4bcb3bb152ebd1"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1742192403/pay_yzSbFQNh8oJoa6cSkxQM?locale=en","secure_link":null,"payment_link_id":"plink_h1btlpLkVr0030VJXs1g"},"profile_id":"pro_qukvQ1whBBb6pdKnzvvN","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-03-18T11:52:46.283Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-03-17T08:06:06.355Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null} </details> 3. Update the payment link in above HTML template ##### Things to test [expected behavior in both the cases - payment link should redirect to the link mentioned in HTML template] - Make a redirection payment, and come back to the iframe - Wait for payment link to be expired, and come back to the iframe ## 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.113.0
f6633a72d5f826804c6a24317f8e5c836b0bc95a
f6633a72d5f826804c6a24317f8e5c836b0bc95a
juspay/hyperswitch
juspay__hyperswitch-7522
Bug: [BUG] Incorrect mapping of attempt status in AuthorizeDotNet connector ### Bug Description When the `capture_method` is `automatic`, AuthorizeDotNet connector first sends a `CapturedPendingSettlement` status which is mapped to `ChargeInitiated` in our codebase. That results in `processing` transaction status in the Hyperswitch's response (in production environment). ### Expected Behavior It should show the status of "succeeded". ### Actual Behavior When the `capture_method` is `automatic`, AuthorizeDotNet connector first sends a `CapturedPendingSettlement` status which is mapped to `ChargeInitiated` in our codebase. That results in `processing` transaction status in the Hyperswitch's response (in production environment). ### Steps To Reproduce Bug can only be seen in production environment. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: MacOS 2. Rust version (output of `rustc --version`): `rustc 1.83.0 (90b35a623 2024-11-26)` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index d7f50aa7405..3ba9e76cc7d 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -1587,8 +1587,9 @@ pub struct AuthorizedotnetRSyncResponse { impl From<SyncStatus> for enums::AttemptStatus { fn from(transaction_status: SyncStatus) -> Self { match transaction_status { - SyncStatus::SettledSuccessfully => Self::Charged, - SyncStatus::CapturedPendingSettlement => Self::CaptureInitiated, + SyncStatus::SettledSuccessfully | SyncStatus::CapturedPendingSettlement => { + Self::Charged + } SyncStatus::AuthorizedPendingCapture => Self::Authorized, SyncStatus::Declined => Self::AuthenticationFailed, SyncStatus::Voided => Self::Voided,
2025-03-13T19:39:20Z
## 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/7522) ## Description <!-- Describe your changes in detail --> Changed the attempt status mapping of `CapturedPendingSettlement` given by AuthorizeDotNet from `ChargeInitiated` to `Charged` ### 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). --> When the capture_method is automatic, AuthorizeDotNet connector first sends a `CapturedPendingSettlement` status which is mapped to `ChargeInitiated` in our codebase. That results in `processing` transaction status in the Hyperswitch's response (in production environment). ## 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 tests are not valid since AuthorizeDotNet directly sends `SettledSuccessfully` status in local/sandbox environment. ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] 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.113.0
3e7db573211ed61eadde3b601575f3472bda2b1f
3e7db573211ed61eadde3b601575f3472bda2b1f
juspay/hyperswitch
juspay__hyperswitch-7520
Bug: [FEATURE]: Add diesel model support as a part of refunds implementation for v2 apis. Add diesel model and storage impl support as a part of refunds implementation for v2 apis.
diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml index 4f02cc4aea8..94913571396 100644 --- a/crates/diesel_models/Cargo.toml +++ b/crates/diesel_models/Cargo.toml @@ -14,6 +14,7 @@ v1 = ["common_utils/v1"] v2 = ["common_utils/v2"] customer_v2 = [] payment_methods_v2 = [] +refunds_v2 = [] [dependencies] async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs index 54e60891532..260b0e4c86a 100644 --- a/crates/diesel_models/src/kv.rs +++ b/crates/diesel_models/src/kv.rs @@ -133,9 +133,14 @@ impl DBOperation { ) .await?, )), + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] Updateable::RefundUpdate(a) => { DBResult::Refund(Box::new(a.orig.update(conn, a.update_data).await?)) } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + Updateable::RefundUpdate(a) => { + DBResult::Refund(Box::new(a.orig.update_with_id(conn, a.update_data).await?)) + } Updateable::AddressUpdate(a) => { DBResult::Address(Box::new(a.orig.update(conn, a.update_data).await?)) } diff --git a/crates/diesel_models/src/query/refund.rs b/crates/diesel_models/src/query/refund.rs index 902916bf98f..adae21c413f 100644 --- a/crates/diesel_models/src/query/refund.rs +++ b/crates/diesel_models/src/query/refund.rs @@ -3,10 +3,19 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, T use super::generics; use crate::{ errors, - refund::{Refund, RefundNew, RefundUpdate, RefundUpdateInternal}, - schema::refund::dsl, + refund::{RefundUpdate, RefundUpdateInternal}, PgPooledConn, StorageResult, }; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +use crate::{ + refund::{Refund, RefundNew}, + schema::refund::dsl, +}; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +use crate::{ + refund::{Refund, RefundNew}, + schema_v2::refund::dsl, +}; impl RefundNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Refund> { @@ -14,6 +23,7 @@ impl RefundNew { } } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] impl Refund { pub async fn update(self, conn: &PgPooledConn, refund: RefundUpdate) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< @@ -127,3 +137,37 @@ impl Refund { .await } } + +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +impl Refund { + pub async fn update_with_id( + self, + conn: &PgPooledConn, + refund: RefundUpdate, + ) -> StorageResult<Self> { + match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( + conn, + self.id.to_owned(), + RefundUpdateInternal::from(refund), + ) + .await + { + Err(error) => match error.current_context() { + errors::DatabaseError::NoFieldsToUpdate => Ok(self), + _ => Err(error), + }, + result => result, + } + } + + pub async fn find_by_global_id( + conn: &PgPooledConn, + id: &common_utils::id_type::GlobalRefundId, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::id.eq(id.to_owned()), + ) + .await + } +} diff --git a/crates/diesel_models/src/query/user/sample_data.rs b/crates/diesel_models/src/query/user/sample_data.rs index b97ea39b82d..8ef4b1e9303 100644 --- a/crates/diesel_models/src/query/user/sample_data.rs +++ b/crates/diesel_models/src/query/user/sample_data.rs @@ -6,16 +6,16 @@ use router_env::logger; #[cfg(feature = "v1")] use crate::schema::{ payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl, + refund::dsl as refund_dsl, }; #[cfg(feature = "v2")] use crate::schema_v2::{ payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl, + refund::dsl as refund_dsl, }; use crate::{ - errors, - schema::{dispute::dsl as dispute_dsl, refund::dsl as refund_dsl}, - user, Dispute, DisputeNew, PaymentAttempt, PaymentIntent, PaymentIntentNew, PgPooledConn, - Refund, RefundNew, StorageResult, + errors, schema::dispute::dsl as dispute_dsl, user, Dispute, DisputeNew, PaymentAttempt, + PaymentIntent, PaymentIntentNew, PgPooledConn, Refund, RefundNew, StorageResult, }; #[cfg(feature = "v1")] diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index ee598bebd2f..6a40baba9dd 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -6,8 +6,13 @@ use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{enums as storage_enums, schema::refund}; +use crate::enums as storage_enums; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +use crate::schema::refund; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +use crate::schema_v2::refund; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive( Clone, Debug, @@ -64,6 +69,58 @@ pub struct Refund { pub issuer_error_message: Option<String>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive( + Clone, + Debug, + Eq, + Identifiable, + Queryable, + Selectable, + PartialEq, + serde::Serialize, + serde::Deserialize, +)] +#[diesel(table_name = refund, primary_key(id), check_for_backend(diesel::pg::Pg))] +pub struct Refund { + pub payment_id: common_utils::id_type::GlobalPaymentId, + pub merchant_id: common_utils::id_type::MerchantId, + pub connector_transaction_id: ConnectorTransactionId, + pub connector: String, + pub connector_refund_id: Option<ConnectorTransactionId>, + pub external_reference_id: Option<String>, + pub refund_type: storage_enums::RefundType, + pub total_amount: MinorUnit, + pub currency: storage_enums::Currency, + pub refund_amount: MinorUnit, + pub refund_status: storage_enums::RefundStatus, + pub sent_to_gateway: bool, + pub refund_error_message: Option<String>, + pub metadata: Option<pii::SecretSerdeValue>, + pub refund_arn: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, + pub description: Option<String>, + pub attempt_id: common_utils::id_type::GlobalAttemptId, + pub refund_reason: Option<String>, + pub refund_error_code: Option<String>, + pub profile_id: Option<common_utils::id_type::ProfileId>, + pub updated_by: String, + pub charges: Option<ChargeRefunds>, + pub organization_id: common_utils::id_type::OrganizationId, + pub split_refunds: Option<common_types::refunds::SplitRefund>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, + pub processor_refund_data: Option<String>, + pub processor_transaction_data: Option<String>, + pub id: common_utils::id_type::GlobalRefundId, + pub merchant_reference_id: common_utils::id_type::RefundReferenceId, + pub connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive( Clone, Debug, @@ -110,6 +167,54 @@ pub struct RefundNew { pub processor_transaction_data: Option<String>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive( + Clone, + Debug, + Eq, + PartialEq, + Insertable, + router_derive::DebugAsDisplay, + serde::Serialize, + serde::Deserialize, + router_derive::Setter, +)] +#[diesel(table_name = refund)] +pub struct RefundNew { + pub merchant_reference_id: common_utils::id_type::RefundReferenceId, + pub payment_id: common_utils::id_type::GlobalPaymentId, + pub merchant_id: common_utils::id_type::MerchantId, + pub id: common_utils::id_type::GlobalRefundId, + pub external_reference_id: Option<String>, + pub connector_transaction_id: ConnectorTransactionId, + pub connector: String, + pub connector_refund_id: Option<ConnectorTransactionId>, + pub refund_type: storage_enums::RefundType, + pub total_amount: MinorUnit, + pub currency: storage_enums::Currency, + pub refund_amount: MinorUnit, + pub refund_status: storage_enums::RefundStatus, + pub sent_to_gateway: bool, + pub metadata: Option<pii::SecretSerdeValue>, + pub refund_arn: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, + pub description: Option<String>, + pub attempt_id: common_utils::id_type::GlobalAttemptId, + pub refund_reason: Option<String>, + pub profile_id: Option<common_utils::id_type::ProfileId>, + pub updated_by: String, + pub connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, + pub charges: Option<ChargeRefunds>, + pub organization_id: common_utils::id_type::OrganizationId, + pub split_refunds: Option<common_types::refunds::SplitRefund>, + pub processor_refund_data: Option<String>, + pub processor_transaction_data: Option<String>, +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum RefundUpdate { Update { @@ -153,6 +258,49 @@ pub enum RefundUpdate { }, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum RefundUpdate { + Update { + connector_refund_id: ConnectorTransactionId, + refund_status: storage_enums::RefundStatus, + sent_to_gateway: bool, + refund_error_message: Option<String>, + refund_arn: String, + updated_by: String, + processor_refund_data: Option<String>, + }, + MetadataAndReasonUpdate { + metadata: Option<pii::SecretSerdeValue>, + reason: Option<String>, + updated_by: String, + }, + StatusUpdate { + connector_refund_id: Option<ConnectorTransactionId>, + sent_to_gateway: bool, + refund_status: storage_enums::RefundStatus, + updated_by: String, + processor_refund_data: Option<String>, + }, + ErrorUpdate { + refund_status: Option<storage_enums::RefundStatus>, + refund_error_message: Option<String>, + refund_error_code: Option<String>, + updated_by: String, + connector_refund_id: Option<ConnectorTransactionId>, + processor_refund_data: Option<String>, + unified_code: Option<String>, + unified_message: Option<String>, + }, + ManualUpdate { + refund_status: Option<storage_enums::RefundStatus>, + refund_error_message: Option<String>, + refund_error_code: Option<String>, + updated_by: String, + }, +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = refund)] pub struct RefundUpdateInternal { @@ -173,6 +321,48 @@ pub struct RefundUpdateInternal { issuer_error_message: Option<String>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] +#[diesel(table_name = refund)] +pub struct RefundUpdateInternal { + connector_refund_id: Option<ConnectorTransactionId>, + refund_status: Option<storage_enums::RefundStatus>, + sent_to_gateway: Option<bool>, + refund_error_message: Option<String>, + refund_arn: Option<String>, + metadata: Option<pii::SecretSerdeValue>, + refund_reason: Option<String>, + refund_error_code: Option<String>, + updated_by: String, + modified_at: PrimitiveDateTime, + processor_refund_data: Option<String>, + unified_code: Option<String>, + unified_message: Option<String>, +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +impl RefundUpdateInternal { + pub fn create_refund(self, source: Refund) -> Refund { + Refund { + connector_refund_id: self.connector_refund_id, + refund_status: self.refund_status.unwrap_or_default(), + sent_to_gateway: self.sent_to_gateway.unwrap_or_default(), + refund_error_message: self.refund_error_message, + refund_arn: self.refund_arn, + metadata: self.metadata, + refund_reason: self.refund_reason, + refund_error_code: self.refund_error_code, + updated_by: self.updated_by, + modified_at: self.modified_at, + processor_refund_data: self.processor_refund_data, + unified_code: self.unified_code, + unified_message: self.unified_message, + ..source + } + } +} + +#[cfg(all(feature = "v2", feature = "refunds_v2"))] impl RefundUpdateInternal { pub fn create_refund(self, source: Refund) -> Refund { Refund { @@ -194,6 +384,7 @@ impl RefundUpdateInternal { } } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] impl From<RefundUpdate> for RefundUpdateInternal { fn from(refund_update: RefundUpdate) -> Self { match refund_update { @@ -320,6 +511,122 @@ impl From<RefundUpdate> for RefundUpdateInternal { } } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +impl From<RefundUpdate> for RefundUpdateInternal { + fn from(refund_update: RefundUpdate) -> Self { + match refund_update { + RefundUpdate::Update { + connector_refund_id, + refund_status, + sent_to_gateway, + refund_error_message, + refund_arn, + updated_by, + processor_refund_data, + } => Self { + connector_refund_id: Some(connector_refund_id), + refund_status: Some(refund_status), + sent_to_gateway: Some(sent_to_gateway), + refund_error_message, + refund_arn: Some(refund_arn), + updated_by, + processor_refund_data, + metadata: None, + refund_reason: None, + refund_error_code: None, + modified_at: common_utils::date_time::now(), + unified_code: None, + unified_message: None, + }, + RefundUpdate::MetadataAndReasonUpdate { + metadata, + reason, + updated_by, + } => Self { + metadata, + refund_reason: reason, + updated_by, + connector_refund_id: None, + refund_status: None, + sent_to_gateway: None, + refund_error_message: None, + refund_arn: None, + refund_error_code: None, + modified_at: common_utils::date_time::now(), + processor_refund_data: None, + unified_code: None, + unified_message: None, + }, + RefundUpdate::StatusUpdate { + connector_refund_id, + sent_to_gateway, + refund_status, + updated_by, + processor_refund_data, + } => Self { + connector_refund_id, + sent_to_gateway: Some(sent_to_gateway), + refund_status: Some(refund_status), + updated_by, + processor_refund_data, + refund_error_message: None, + refund_arn: None, + metadata: None, + refund_reason: None, + refund_error_code: None, + modified_at: common_utils::date_time::now(), + unified_code: None, + unified_message: None, + }, + RefundUpdate::ErrorUpdate { + refund_status, + refund_error_message, + refund_error_code, + unified_code, + unified_message, + updated_by, + connector_refund_id, + processor_refund_data, + } => Self { + refund_status, + refund_error_message, + refund_error_code, + updated_by, + connector_refund_id, + processor_refund_data, + sent_to_gateway: None, + refund_arn: None, + metadata: None, + refund_reason: None, + modified_at: common_utils::date_time::now(), + unified_code, + unified_message, + }, + RefundUpdate::ManualUpdate { + refund_status, + refund_error_message, + refund_error_code, + updated_by, + } => Self { + refund_status, + refund_error_message, + refund_error_code, + updated_by, + connector_refund_id: None, + sent_to_gateway: None, + refund_arn: None, + metadata: None, + refund_reason: None, + modified_at: common_utils::date_time::now(), + processor_refund_data: None, + unified_code: None, + unified_message: None, + }, + } + } +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] impl RefundUpdate { pub fn apply_changeset(self, source: Refund) -> Refund { let RefundUpdateInternal { @@ -360,6 +667,43 @@ impl RefundUpdate { } } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +impl RefundUpdate { + pub fn apply_changeset(self, source: Refund) -> Refund { + let RefundUpdateInternal { + connector_refund_id, + refund_status, + sent_to_gateway, + refund_error_message, + refund_arn, + metadata, + refund_reason, + refund_error_code, + updated_by, + modified_at: _, + processor_refund_data, + unified_code, + unified_message, + } = self.into(); + Refund { + connector_refund_id: connector_refund_id.or(source.connector_refund_id), + refund_status: refund_status.unwrap_or(source.refund_status), + sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway), + refund_error_message: refund_error_message.or(source.refund_error_message), + refund_error_code: refund_error_code.or(source.refund_error_code), + refund_arn: refund_arn.or(source.refund_arn), + metadata: metadata.or(source.metadata), + refund_reason: refund_reason.or(source.refund_reason), + updated_by, + modified_at: common_utils::date_time::now(), + processor_refund_data: processor_refund_data.or(source.processor_refund_data), + unified_code: unified_code.or(source.unified_code), + unified_message: unified_message.or(source.unified_message), + ..source + } + } +} + #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct RefundCoreWorkflow { pub refund_internal_reference_id: String, @@ -379,6 +723,16 @@ impl common_utils::events::ApiEventMetric for Refund { } } +#[cfg(feature = "v2")] +impl common_utils::events::ApiEventMetric for Refund { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + Some(common_utils::events::ApiEventsType::Refund { + payment_id: self.payment_id.clone(), + refund_id: self.id.clone(), + }) + } +} + impl ConnectorTransactionIdTrait for Refund { fn get_optional_connector_refund_id(&self) -> Option<&String> { match self diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 5d028ad5214..d97d4fec68a 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1160,11 +1160,7 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - refund (merchant_id, refund_id) { - #[max_length = 64] - internal_reference_id -> Varchar, - #[max_length = 64] - refund_id -> Varchar, + refund (id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] @@ -1200,8 +1196,6 @@ diesel::table! { profile_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, - #[max_length = 32] - merchant_connector_id -> Nullable<Varchar>, charges -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, @@ -1212,6 +1206,12 @@ diesel::table! { unified_message -> Nullable<Varchar>, processor_refund_data -> Nullable<Text>, processor_transaction_data -> Nullable<Text>, + #[max_length = 64] + id -> Varchar, + #[max_length = 64] + merchant_reference_id -> Varchar, + #[max_length = 64] + connector_id -> Nullable<Varchar>, } } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 2012028169c..780d4509db7 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -33,12 +33,13 @@ payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors payout_retry = ["payouts"] recon = ["email", "api_models/recon"] retry = [] -v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","scheduler/v2"] +v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2","hyperswitch_interfaces/v2", "common_types/v2","revenue_recovery","refunds_v2","scheduler/v2"] v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1","scheduler/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"] revenue_recovery =["api_models/revenue_recovery","hyperswitch_interfaces/revenue_recovery","hyperswitch_domain_models/revenue_recovery","hyperswitch_connectors/revenue_recovery"] +refunds_v2 = ["diesel_models/refunds_v2", "storage_impl/refunds_v2"] # Partial Auth # The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request. diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index d06d13a3123..9b72ba26c26 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2647,6 +2647,7 @@ impl CaptureInterface for KafkaStore { #[async_trait::async_trait] impl RefundInterface for KafkaStore { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, @@ -2662,6 +2663,7 @@ impl RefundInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, @@ -2673,6 +2675,7 @@ impl RefundInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &id_type::MerchantId, @@ -2684,6 +2687,7 @@ impl RefundInterface for KafkaStore { .await } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &id_type::MerchantId, @@ -2722,6 +2726,7 @@ impl RefundInterface for KafkaStore { Ok(refund) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &id_type::MerchantId, @@ -2737,6 +2742,17 @@ impl RefundInterface for KafkaStore { .await } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn find_refund_by_id( + &self, + id: &id_type::GlobalRefundId, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<storage::Refund, errors::StorageError> { + self.diesel_store + .find_refund_by_id(id, storage_scheme) + .await + } + async fn insert_refund( &self, new: storage::RefundNew, @@ -2754,7 +2770,11 @@ impl RefundInterface for KafkaStore { Ok(refund) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn filter_refund_by_constraints( &self, merchant_id: &id_type::MerchantId, @@ -2774,7 +2794,11 @@ impl RefundInterface for KafkaStore { .await } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn filter_refund_by_meta_constraints( &self, merchant_id: &id_type::MerchantId, @@ -2786,7 +2810,11 @@ impl RefundInterface for KafkaStore { .await } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn get_refund_status_with_count( &self, merchant_id: &id_type::MerchantId, @@ -2799,7 +2827,11 @@ impl RefundInterface for KafkaStore { .await } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn get_total_count_of_refunds( &self, merchant_id: &id_type::MerchantId, diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 1f54eeb5fdc..211f8ddbc48 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -17,6 +17,7 @@ const MAX_LIMIT: usize = 100; #[async_trait::async_trait] pub trait RefundInterface { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, @@ -24,6 +25,7 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, @@ -31,6 +33,7 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -38,6 +41,7 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -53,6 +57,7 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -60,13 +65,24 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError>; + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn find_refund_by_id( + &self, + id: &common_utils::id_type::GlobalRefundId, + storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError>; + async fn insert_refund( &self, new: storage_types::RefundNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -76,7 +92,11 @@ pub trait RefundInterface { offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>; - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -84,7 +104,11 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError>; - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -93,7 +117,11 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError>; - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -320,6 +348,7 @@ mod storage { }; #[async_trait::async_trait] impl RefundInterface for Store { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_internal_reference_id_merchant_id( &self, @@ -376,6 +405,7 @@ mod storage { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn insert_refund( &self, @@ -529,6 +559,20 @@ mod storage { } } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[instrument(skip_all)] + async fn insert_refund( + &self, + new: storage_types::RefundNew, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + new.insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_transaction_id( &self, @@ -588,6 +632,7 @@ mod storage { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn update_refund( &self, @@ -652,6 +697,21 @@ mod storage { } } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[instrument(skip_all)] + async fn update_refund( + &self, + this: storage_types::Refund, + refund: storage_types::RefundUpdate, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + this.update_with_id(&conn, refund) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_merchant_id_refund_id( &self, @@ -702,6 +762,7 @@ mod storage { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, @@ -760,6 +821,7 @@ mod storage { } } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_payment_id_merchant_id( &self, @@ -807,7 +869,24 @@ mod storage { } } - #[cfg(feature = "olap")] + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[instrument(skip_all)] + async fn find_refund_by_id( + &self, + id: &common_utils::id_type::GlobalRefundId, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage_types::Refund::find_by_global_id(&conn, id) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, @@ -829,7 +908,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] #[instrument(skip_all)] async fn filter_refund_by_meta_constraints( &self, @@ -843,7 +926,11 @@ mod storage { .map_err(|error|report!(errors::StorageError::from(error))) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] #[instrument(skip_all)] async fn get_refund_status_with_count( &self, @@ -858,7 +945,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, @@ -880,6 +971,7 @@ mod storage { #[async_trait::async_trait] impl RefundInterface for MockDb { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, @@ -899,6 +991,7 @@ impl RefundInterface for MockDb { }) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn insert_refund( &self, new: storage_types::RefundNew, @@ -950,6 +1043,56 @@ impl RefundInterface for MockDb { refunds.push(refund.clone()); Ok(refund) } + + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn insert_refund( + &self, + new: storage_types::RefundNew, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let mut refunds = self.refunds.lock().await; + let current_time = common_utils::date_time::now(); + + let refund = storage_types::Refund { + id: new.id, + merchant_reference_id: new.merchant_reference_id, + payment_id: new.payment_id, + merchant_id: new.merchant_id, + attempt_id: new.attempt_id, + connector_transaction_id: new.connector_transaction_id, + connector: new.connector, + connector_refund_id: new.connector_refund_id, + external_reference_id: new.external_reference_id, + refund_type: new.refund_type, + total_amount: new.total_amount, + currency: new.currency, + refund_amount: new.refund_amount, + refund_status: new.refund_status, + sent_to_gateway: new.sent_to_gateway, + refund_error_message: None, + refund_error_code: None, + metadata: new.metadata, + refund_arn: new.refund_arn.clone(), + created_at: new.created_at, + modified_at: current_time, + description: new.description, + refund_reason: new.refund_reason.clone(), + profile_id: new.profile_id, + updated_by: new.updated_by, + connector_id: new.connector_id, + charges: new.charges, + split_refunds: new.split_refunds, + organization_id: new.organization_id, + unified_code: None, + unified_message: None, + processor_refund_data: new.processor_refund_data.clone(), + processor_transaction_data: new.processor_transaction_data.clone(), + }; + refunds.push(refund.clone()); + Ok(refund) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -968,6 +1111,7 @@ impl RefundInterface for MockDb { .collect::<Vec<_>>()) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn update_refund( &self, this: storage_types::Refund, @@ -990,6 +1134,30 @@ impl RefundInterface for MockDb { }) } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn update_refund( + &self, + this: storage_types::Refund, + refund: storage_types::RefundUpdate, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + self.refunds + .lock() + .await + .iter_mut() + .find(|refund| this.merchant_reference_id == refund.merchant_reference_id) + .map(|r| { + let refund_updated = RefundUpdateInternal::from(refund).create_refund(r.clone()); + *r = refund_updated.clone(); + refund_updated + }) + .ok_or_else(|| { + errors::StorageError::ValueNotFound("cannot find refund to update".to_string()) + .into() + }) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -1007,6 +1175,7 @@ impl RefundInterface for MockDb { }) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -1032,6 +1201,7 @@ impl RefundInterface for MockDb { }) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, @@ -1047,7 +1217,28 @@ impl RefundInterface for MockDb { .collect::<Vec<_>>()) } - #[cfg(feature = "olap")] + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn find_refund_by_id( + &self, + id: &common_utils::id_type::GlobalRefundId, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let refunds = self.refunds.lock().await; + + refunds + .iter() + .find(|refund| refund.id == *id) + .cloned() + .ok_or_else(|| { + errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() + }) + } + + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -1162,7 +1353,11 @@ impl RefundInterface for MockDb { Ok(filtered_refunds) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn filter_refund_by_meta_constraints( &self, _merchant_id: &common_utils::id_type::MerchantId, @@ -1209,7 +1404,11 @@ impl RefundInterface for MockDb { Ok(refund_meta_data) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn get_refund_status_with_count( &self, _merchant_id: &common_utils::id_type::MerchantId, @@ -1255,7 +1454,11 @@ impl RefundInterface for MockDb { Ok(result) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs index a7e37930cf2..19635b2d8c2 100644 --- a/crates/router/src/services/kafka/refund.rs +++ b/crates/router/src/services/kafka/refund.rs @@ -5,6 +5,9 @@ use common_utils::{ use diesel_models::{enums as storage_enums, refund::Refund}; use time::OffsetDateTime; +use crate::events; + +#[cfg(feature = "v1")] #[derive(serde::Serialize, Debug)] pub struct KafkaRefund<'a> { pub internal_reference_id: &'a String, @@ -35,6 +38,7 @@ pub struct KafkaRefund<'a> { pub organization_id: &'a id_type::OrganizationId, } +#[cfg(feature = "v1")] impl<'a> KafkaRefund<'a> { pub fn from_storage(refund: &'a Refund) -> Self { Self { @@ -66,6 +70,70 @@ impl<'a> KafkaRefund<'a> { } } +#[cfg(feature = "v2")] +#[derive(serde::Serialize, Debug)] +pub struct KafkaRefund<'a> { + pub id: &'a id_type::GlobalRefundId, + pub merchant_reference_id: &'a id_type::RefundReferenceId, + pub payment_id: &'a id_type::GlobalPaymentId, + pub merchant_id: &'a id_type::MerchantId, + pub connector_transaction_id: &'a String, + pub connector: &'a String, + pub connector_refund_id: Option<&'a String>, + pub external_reference_id: Option<&'a String>, + pub refund_type: &'a storage_enums::RefundType, + pub total_amount: &'a MinorUnit, + pub currency: &'a storage_enums::Currency, + pub refund_amount: &'a MinorUnit, + pub refund_status: &'a storage_enums::RefundStatus, + pub sent_to_gateway: &'a bool, + pub refund_error_message: Option<&'a String>, + pub refund_arn: Option<&'a String>, + #[serde(default, with = "time::serde::timestamp")] + pub created_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp")] + pub modified_at: OffsetDateTime, + pub description: Option<&'a String>, + pub attempt_id: &'a id_type::GlobalAttemptId, + pub refund_reason: Option<&'a String>, + pub refund_error_code: Option<&'a String>, + pub profile_id: Option<&'a id_type::ProfileId>, + pub organization_id: &'a id_type::OrganizationId, +} + +#[cfg(feature = "v2")] +impl<'a> KafkaRefund<'a> { + pub fn from_storage(refund: &'a Refund) -> Self { + Self { + id: &refund.id, + merchant_reference_id: &refund.merchant_reference_id, + payment_id: &refund.payment_id, + merchant_id: &refund.merchant_id, + connector_transaction_id: refund.get_connector_transaction_id(), + connector: &refund.connector, + connector_refund_id: refund.get_optional_connector_refund_id(), + external_reference_id: refund.external_reference_id.as_ref(), + refund_type: &refund.refund_type, + total_amount: &refund.total_amount, + currency: &refund.currency, + refund_amount: &refund.refund_amount, + refund_status: &refund.refund_status, + sent_to_gateway: &refund.sent_to_gateway, + refund_error_message: refund.refund_error_message.as_ref(), + refund_arn: refund.refund_arn.as_ref(), + created_at: refund.created_at.assume_utc(), + modified_at: refund.modified_at.assume_utc(), + description: refund.description.as_ref(), + attempt_id: &refund.attempt_id, + refund_reason: refund.refund_reason.as_ref(), + refund_error_code: refund.refund_error_code.as_ref(), + profile_id: refund.profile_id.as_ref(), + organization_id: &refund.organization_id, + } + } +} + +#[cfg(feature = "v1")] impl super::KafkaMessage for KafkaRefund<'_> { fn key(&self) -> String { format!( @@ -77,7 +145,24 @@ impl super::KafkaMessage for KafkaRefund<'_> { ) } - fn event_type(&self) -> crate::events::EventType { - crate::events::EventType::Refund + fn event_type(&self) -> events::EventType { + events::EventType::Refund + } +} + +#[cfg(feature = "v2")] +impl super::KafkaMessage for KafkaRefund<'_> { + fn key(&self) -> String { + format!( + "{}_{}_{}_{}", + self.merchant_id.get_string_repr(), + self.payment_id.get_string_repr(), + self.attempt_id.get_string_repr(), + self.merchant_reference_id.get_string_repr() + ) + } + + fn event_type(&self) -> events::EventType { + events::EventType::Refund } } diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs index b9b3db17b58..34ed0b85c55 100644 --- a/crates/router/src/services/kafka/refund_event.rs +++ b/crates/router/src/services/kafka/refund_event.rs @@ -5,6 +5,9 @@ use common_utils::{ use diesel_models::{enums as storage_enums, refund::Refund}; use time::OffsetDateTime; +use crate::events; + +#[cfg(feature = "v1")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaRefundEvent<'a> { @@ -36,6 +39,7 @@ pub struct KafkaRefundEvent<'a> { pub organization_id: &'a id_type::OrganizationId, } +#[cfg(feature = "v1")] impl<'a> KafkaRefundEvent<'a> { pub fn from_storage(refund: &'a Refund) -> Self { Self { @@ -67,6 +71,71 @@ impl<'a> KafkaRefundEvent<'a> { } } +#[cfg(feature = "v2")] +#[serde_with::skip_serializing_none] +#[derive(serde::Serialize, Debug)] +pub struct KafkaRefundEvent<'a> { + pub id: &'a id_type::GlobalRefundId, + pub merchant_reference_id: &'a id_type::RefundReferenceId, + pub payment_id: &'a id_type::GlobalPaymentId, + pub merchant_id: &'a id_type::MerchantId, + pub connector_transaction_id: &'a String, + pub connector: &'a String, + pub connector_refund_id: Option<&'a String>, + pub external_reference_id: Option<&'a String>, + pub refund_type: &'a storage_enums::RefundType, + pub total_amount: &'a MinorUnit, + pub currency: &'a storage_enums::Currency, + pub refund_amount: &'a MinorUnit, + pub refund_status: &'a storage_enums::RefundStatus, + pub sent_to_gateway: &'a bool, + pub refund_error_message: Option<&'a String>, + pub refund_arn: Option<&'a String>, + #[serde(default, with = "time::serde::timestamp::nanoseconds")] + pub created_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::nanoseconds")] + pub modified_at: OffsetDateTime, + pub description: Option<&'a String>, + pub attempt_id: &'a id_type::GlobalAttemptId, + pub refund_reason: Option<&'a String>, + pub refund_error_code: Option<&'a String>, + pub profile_id: Option<&'a id_type::ProfileId>, + pub organization_id: &'a id_type::OrganizationId, +} + +#[cfg(feature = "v2")] +impl<'a> KafkaRefundEvent<'a> { + pub fn from_storage(refund: &'a Refund) -> Self { + Self { + id: &refund.id, + merchant_reference_id: &refund.merchant_reference_id, + payment_id: &refund.payment_id, + merchant_id: &refund.merchant_id, + connector_transaction_id: refund.get_connector_transaction_id(), + connector: &refund.connector, + connector_refund_id: refund.get_optional_connector_refund_id(), + external_reference_id: refund.external_reference_id.as_ref(), + refund_type: &refund.refund_type, + total_amount: &refund.total_amount, + currency: &refund.currency, + refund_amount: &refund.refund_amount, + refund_status: &refund.refund_status, + sent_to_gateway: &refund.sent_to_gateway, + refund_error_message: refund.refund_error_message.as_ref(), + refund_arn: refund.refund_arn.as_ref(), + created_at: refund.created_at.assume_utc(), + modified_at: refund.modified_at.assume_utc(), + description: refund.description.as_ref(), + attempt_id: &refund.attempt_id, + refund_reason: refund.refund_reason.as_ref(), + refund_error_code: refund.refund_error_code.as_ref(), + profile_id: refund.profile_id.as_ref(), + organization_id: &refund.organization_id, + } + } +} + +#[cfg(feature = "v1")] impl super::KafkaMessage for KafkaRefundEvent<'_> { fn key(&self) -> String { format!( @@ -77,8 +146,23 @@ impl super::KafkaMessage for KafkaRefundEvent<'_> { self.refund_id ) } + fn event_type(&self) -> events::EventType { + events::EventType::Refund + } +} - fn event_type(&self) -> crate::events::EventType { - crate::events::EventType::Refund +#[cfg(feature = "v2")] +impl super::KafkaMessage for KafkaRefundEvent<'_> { + fn key(&self) -> String { + format!( + "{}_{}_{}_{}", + self.merchant_id.get_string_repr(), + self.payment_id.get_string_repr(), + self.attempt_id.get_string_repr(), + self.merchant_reference_id.get_string_repr() + ) + } + fn event_type(&self) -> events::EventType { + events::EventType::Refund } } diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs index e46fc1a3f47..646b2742d5b 100644 --- a/crates/router/src/types/storage/refund.rs +++ b/crates/router/src/types/storage/refund.rs @@ -18,6 +18,7 @@ use crate::{connection::PgPooledConn, logger}; #[async_trait::async_trait] pub trait RefundDbExt: Sized { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -26,18 +27,21 @@ pub trait RefundDbExt: Sized { offset: i64, ) -> CustomResult<Vec<Self>, errors::DatabaseError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_meta_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &common_utils::types::TimeRange, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refunds_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &refunds::RefundListConstraints, ) -> CustomResult<i64, errors::DatabaseError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refund_status_with_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -48,6 +52,7 @@ pub trait RefundDbExt: Sized { #[async_trait::async_trait] impl RefundDbExt for Refund { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -159,6 +164,7 @@ impl RefundDbExt for Refund { .attach_printable_lazy(|| "Error filtering records by predicate") } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_meta_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -214,6 +220,7 @@ impl RefundDbExt for Refund { Ok(meta) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refunds_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -302,6 +309,7 @@ impl RefundDbExt for Refund { .attach_printable_lazy(|| "Error filtering count of refunds") } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refund_status_with_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml index ac3598cea58..06b551d8312 100644 --- a/crates/storage_impl/Cargo.toml +++ b/crates/storage_impl/Cargo.toml @@ -17,6 +17,7 @@ v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "comm v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "common_utils/v2"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"] payment_methods_v2 = ["diesel_models/payment_methods_v2", "api_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2"] +refunds_v2 = ["diesel_models/refunds_v2"] [dependencies] # First Party dependencies diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 13b4671e863..657114d1067 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -346,6 +346,7 @@ impl UniqueConstraints for diesel_models::PaymentAttempt { } } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] impl UniqueConstraints for diesel_models::Refund { fn unique_constraints(&self) -> Vec<String> { vec![format!( @@ -359,6 +360,16 @@ impl UniqueConstraints for diesel_models::Refund { } } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +impl UniqueConstraints for diesel_models::Refund { + fn unique_constraints(&self) -> Vec<String> { + vec![self.id.get_string_repr().to_owned()] + } + fn table_name(&self) -> &str { + "Refund" + } +} + impl UniqueConstraints for diesel_models::ReverseLookup { fn unique_constraints(&self) -> Vec<String> { vec![format!("reverselookup_{}", self.lookup_id)] diff --git a/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/down.sql b/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/down.sql index 92f74b1d9ac..e3c87773716 100644 --- a/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/down.sql +++ b/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/down.sql @@ -52,4 +52,9 @@ ALTER TABLE merchant_connector_account ALTER TABLE payment_methods DROP COLUMN IF EXISTS locker_fingerprint_id, DROP COLUMN IF EXISTS payment_method_type_v2, - DROP COLUMN IF EXISTS payment_method_subtype; \ No newline at end of file + DROP COLUMN IF EXISTS payment_method_subtype; + +ALTER TABLE refund + DROP COLUMN IF EXISTS id, + DROP COLUMN IF EXISTS merchant_reference_id, + DROP COLUMN IF EXISTS connector_id; \ No newline at end of file diff --git a/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql b/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql index 3094cdb3320..1dcedbff563 100644 --- a/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql +++ b/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql @@ -62,4 +62,9 @@ ALTER TABLE merchant_connector_account ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_type_v2 VARCHAR(64), - ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64); \ No newline at end of file + ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64); + +ALTER TABLE refund + ADD COLUMN IF NOT EXISTS id VARCHAR(64), + ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64), + ADD COLUMN IF NOT EXISTS connector_id VARCHAR(64); \ No newline at end of file diff --git a/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/down.sql b/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/down.sql index 10fd9adfa55..c0b0efbd385 100644 --- a/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/down.sql +++ b/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/down.sql @@ -37,3 +37,7 @@ ALTER TABLE payment_attempt ---------------------- Payment Methods ---------------------- ALTER TABLE payment_methods ADD PRIMARY KEY (payment_method_id); + +---------------------- Refunds ---------------------- +ALTER TABLE refund + ADD PRIMARY KEY (refund_id,merchant_id); \ No newline at end of file diff --git a/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql b/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql index e348f2e1cbb..731d488297e 100644 --- a/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql +++ b/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql @@ -37,3 +37,7 @@ ALTER TABLE payment_attempt ALTER TABLE payment_methods DROP CONSTRAINT payment_methods_pkey, ALTER COLUMN payment_method_id DROP NOT NULL; + +ALTER TABLE refund + DROP CONSTRAINT refund_pkey, + ALTER COLUMN refund_id DROP NOT NULL; \ No newline at end of file diff --git a/v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/down.sql b/v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/down.sql similarity index 87% rename from v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/down.sql rename to v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/down.sql index 1941d9c1b8e..06b78440d17 100644 --- a/v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/down.sql +++ b/v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/down.sql @@ -24,4 +24,7 @@ ALTER TABLE payment_attempt ALTER COLUMN net_amount DROP NOT NULL, ALTER COLUMN authentication_type DROP NOT NULL, ALTER COLUMN payment_method_type_v2 DROP NOT NULL, - ALTER COLUMN payment_method_subtype DROP NOT NULL; \ No newline at end of file + ALTER COLUMN payment_method_subtype DROP NOT NULL; + +ALTER TABLE refund + ALTER COLUMN merchant_reference_id DROP NOT NULL; \ No newline at end of file diff --git a/v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/up.sql b/v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/up.sql similarity index 83% rename from v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/up.sql rename to v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/up.sql index 36fc7d2893d..3641d2bdab6 100644 --- a/v2_migrations/2024-08-28-081839_add_not_null_constraints_to_v2_columns/up.sql +++ b/v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/up.sql @@ -23,4 +23,8 @@ ALTER TABLE payment_attempt ALTER COLUMN net_amount SET NOT NULL, ALTER COLUMN authentication_type SET NOT NULL, ALTER COLUMN payment_method_type_v2 SET NOT NULL, - ALTER COLUMN payment_method_subtype SET NOT NULL; \ No newline at end of file + ALTER COLUMN payment_method_subtype SET NOT NULL; + +-- This migration is to make fields mandatory in refund table +ALTER TABLE refund + ALTER COLUMN merchant_reference_id SET NOT NULL; \ No newline at end of file diff --git a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql index 9b04dd6d3f5..a48c2b660f5 100644 --- a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql +++ b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql @@ -65,3 +65,7 @@ ALTER TABLE payment_attempt ALTER COLUMN id DROP NOT NULL; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP CONSTRAINT payment_methods_pkey; ALTER TABLE payment_methods ALTER COLUMN id DROP NOT NULL; + +------------------------ Refunds ----------------------- +ALTER TABLE refund DROP CONSTRAINT refund_pkey; +ALTER TABLE refund ALTER COLUMN id DROP NOT NULL; \ No newline at end of file diff --git a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql index 3b155115119..df0c434d68f 100644 --- a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql +++ b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql @@ -76,3 +76,8 @@ ADD PRIMARY KEY (id); -- Add primary key constraint ALTER TABLE payment_methods ADD PRIMARY KEY (id); + +------------------------ Refunds ----------------------- +-- Add primary key constraint +ALTER TABLE refund +ADD PRIMARY KEY (id); \ No newline at end of file diff --git a/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql index efcb56101f9..483ef12a276 100644 --- a/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql @@ -130,4 +130,9 @@ ALTER TABLE payment_methods ALTER TABLE refund ADD COLUMN connector_refund_data VARCHAR(512), ADD COLUMN connector_transaction_data VARCHAR(512); -ALTER TABLE captures ADD COLUMN connector_capture_data VARCHAR(512); \ No newline at end of file +ALTER TABLE captures ADD COLUMN connector_capture_data VARCHAR(512); + +ALTER TABLE refund + ADD COLUMN IF NOT EXISTS internal_reference_id VARCHAR(64), + ADD COLUMN IF NOT EXISTS refund_id VARCHAR(64), + ADD COLUMN IF NOT EXISTS merchant_connector_id VARCHAR(64); \ No newline at end of file diff --git a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql index cbb2b264d45..69357bb04ac 100644 --- a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql @@ -121,3 +121,9 @@ ALTER TABLE refund DROP COLUMN connector_refund_data, -- Run below queries only when V1 is deprecated ALTER TABLE captures DROP COLUMN connector_capture_data; + +-- Run below queries only when V1 is deprecated +ALTER TABLE refund + DROP COLUMN IF EXISTS internal_reference_id, + DROP COLUMN IF EXISTS refund_id, + DROP COLUMN IF EXISTS merchant_connector_id;
2025-03-12T16:18:08Z
## 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 is a part of v2 implementation of refunds. This PR contains the necessary database schema refactoring as well as handling this in the storage_impl crate. ### 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). --> Merging this PR would add db support for refunds in v2 apis. ## 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)? --> Cannot be tested because the core flow is not implemented for the refunds in V2 APIs, will be taking that in upcoming PRs. ## 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.113.0
afca506369685ab63d1b6bccd5f2e2dbae50ebf9
afca506369685ab63d1b6bccd5f2e2dbae50ebf9
juspay/hyperswitch
juspay__hyperswitch-7518
Bug: feat(router): Add `psp_tokenization_enabled` field in Customer Saved Payment Methods List Required to show whether `psp_tokenization` is enabled for a saved payment method
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index dbe13e3776e..0ae089c5ea0 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -2834,7 +2834,7 @@ } }, "/v2/customers/{id}/saved-payment-methods": { - "delete": { + "get": { "tags": [ "Payment Methods" ], @@ -7666,6 +7666,7 @@ "prophetpay", "rapyd", "razorpay", + "recurly", "shift4", "square", "stax", @@ -8651,7 +8652,8 @@ "recurring_enabled", "created", "requires_cvv", - "is_default" + "is_default", + "psp_tokenization_enabled" ], "properties": { "id": { @@ -8730,6 +8732,10 @@ } ], "nullable": true + }, + "psp_tokenization_enabled": { + "type": "boolean", + "description": "Whether psp_tokenization is enabled for the payment_method, this will be true when at least\none multi-use token with status `Active` is available for the payment method" } } }, @@ -11603,7 +11609,7 @@ "product_type": { "allOf": [ { - "$ref": "#/components/schemas/api_enums.MerchantProductType" + "$ref": "#/components/schemas/MerchantProductType" } ], "nullable": true @@ -11745,7 +11751,7 @@ "product_type": { "allOf": [ { - "$ref": "#/components/schemas/api_enums.MerchantProductType" + "$ref": "#/components/schemas/MerchantProductType" } ], "nullable": true @@ -12359,6 +12365,17 @@ }, "additionalProperties": false }, + "MerchantProductType": { + "type": "string", + "enum": [ + "orchestration", + "vault", + "recon", + "recovery", + "cost_observability", + "dynamic_routing" + ] + }, "MerchantRecipientData": { "oneOf": [ { @@ -12581,6 +12598,69 @@ } } }, + "NetworkTokenDetailsPaymentMethod": { + "type": "object", + "properties": { + "last4_digits": { + "type": "string", + "nullable": true + }, + "issuer_country": { + "type": "string", + "nullable": true + }, + "network_token_expiry_month": { + "type": "string", + "nullable": true + }, + "network_token_expiry_year": { + "type": "string", + "nullable": true + }, + "nick_name": { + "type": "string", + "nullable": true + }, + "card_holder_name": { + "type": "string", + "nullable": true + }, + "card_isin": { + "type": "string", + "nullable": true + }, + "card_issuer": { + "type": "string", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_type": { + "type": "string", + "nullable": true + }, + "saved_to_locker": { + "type": "boolean" + } + } + }, + "NetworkTokenResponse": { + "type": "object", + "required": [ + "payment_method_data" + ], + "properties": { + "payment_method_data": { + "$ref": "#/components/schemas/NetworkTokenDetailsPaymentMethod" + } + } + }, "NetworkTokenization": { "type": "object", "description": "The network tokenization configuration for creating the payment method session", @@ -13968,7 +14048,7 @@ "PaymentConnectorTransmission": { "type": "string", "enum": [ - "ConnectorCallFailed", + "ConnectorCallUnsuccessful", "ConnectorCallSucceeded" ] }, @@ -20385,6 +20465,7 @@ "prophetpay", "rapyd", "razorpay", + "recurly", "riskified", "shift4", "signifyd", diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 917efcea984..fa4ce7ae5eb 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -9765,6 +9765,7 @@ "prophetpay", "rapyd", "razorpay", + "recurly", "shift4", "square", "stax", @@ -13933,7 +13934,7 @@ "product_type": { "allOf": [ { - "$ref": "#/components/schemas/api_enums.MerchantProductType" + "$ref": "#/components/schemas/MerchantProductType" } ], "nullable": true @@ -14174,7 +14175,7 @@ "product_type": { "allOf": [ { - "$ref": "#/components/schemas/api_enums.MerchantProductType" + "$ref": "#/components/schemas/MerchantProductType" } ], "nullable": true @@ -15089,6 +15090,17 @@ }, "additionalProperties": false }, + "MerchantProductType": { + "type": "string", + "enum": [ + "orchestration", + "vault", + "recon", + "recovery", + "cost_observability", + "dynamic_routing" + ] + }, "MerchantRecipientData": { "oneOf": [ { @@ -24881,6 +24893,7 @@ "prophetpay", "rapyd", "razorpay", + "recurly", "riskified", "shift4", "signifyd", diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index b6f1e0a8b96..b3d21c5a0b6 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -113,7 +113,7 @@ pub struct MerchantAccountCreate { pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, /// Product Type of this merchant account - #[schema(value_type = Option<api_enums::MerchantProductType>)] + #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } @@ -198,6 +198,7 @@ pub struct MerchantAccountCreateWithoutOrgId { #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, + #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } @@ -560,7 +561,7 @@ pub struct MerchantAccountResponse { pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, /// Product Type of this merchant account - #[schema(value_type = Option<api_enums::MerchantProductType>)] + #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } @@ -596,7 +597,7 @@ pub struct MerchantAccountResponse { pub recon_status: api_enums::ReconStatus, /// Product Type of this merchant account - #[schema(value_type = Option<api_enums::MerchantProductType>)] + #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 6b9b35ac2c0..d665337fda0 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -980,16 +980,21 @@ pub struct CardDetailsPaymentMethod { pub saved_to_locker: bool, } -#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct NetworkTokenDetailsPaymentMethod { pub last4_digits: Option<String>, pub issuer_country: Option<String>, + #[schema(value_type = Option<String>)] pub network_token_expiry_month: Option<masking::Secret<String>>, + #[schema(value_type = Option<String>)] pub network_token_expiry_year: Option<masking::Secret<String>>, + #[schema(value_type = Option<String>)] pub nick_name: Option<masking::Secret<String>>, + #[schema(value_type = Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, pub card_isin: Option<String>, pub card_issuer: Option<String>, + #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] @@ -2019,6 +2024,10 @@ pub struct CustomerPaymentMethod { ///The network token details for the payment method pub network_tokenization: Option<NetworkTokenResponse>, + + /// Whether psp_tokenization is enabled for the payment_method, this will be true when at least + /// one multi-use token with status `Active` is available for the payment method + pub psp_tokenization_enabled: bool, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 1109c0ca75e..20d1aa64745 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -320,6 +320,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::PaymentLinkDetailsLayout, api_models::enums::PaymentMethodStatus, api_models::enums::UIWidgetFormLayout, + api_models::enums::MerchantProductType, api_models::enums::PaymentConnectorCategory, api_models::enums::CardDiscovery, api_models::enums::FeatureStatus, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 8a122b5fe8b..5bbd8dee4b4 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -259,6 +259,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::PaymentMethod, api_models::enums::PaymentMethodIssuerCode, api_models::enums::MandateStatus, + api_models::enums::MerchantProductType, api_models::enums::PaymentExperience, api_models::enums::BankNames, api_models::enums::BankType, @@ -527,6 +528,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodSessionRequest, api_models::payment_methods::PaymentMethodSessionResponse, api_models::payment_methods::PaymentMethodsSessionUpdateRequest, + api_models::payment_methods::NetworkTokenResponse, + api_models::payment_methods::NetworkTokenDetailsPaymentMethod, api_models::payment_methods::TokenizeCardRequest, api_models::payment_methods::TokenizeDataRequest, api_models::payment_methods::TokenizePaymentMethodRequest, diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rs index 9304afc69d3..cf1cd15346f 100644 --- a/crates/openapi/src/routes/payment_method.rs +++ b/crates/openapi/src/routes/payment_method.rs @@ -326,7 +326,7 @@ pub async fn payment_method_delete_api() {} /// /// List the payment methods saved for a customer #[utoipa::path( - delete, + get, path = "/v2/customers/{id}/saved-payment-methods", params ( ("id" = String, Path, description = "The unique identifier for the customer"), diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 87f7e38c935..a7817329607 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -985,6 +985,15 @@ impl transformers::ForeignTryFrom<domain::PaymentMethod> for api::CustomerPaymen // TODO: check how we can get this field let recurring_enabled = true; + let psp_tokenization_enabled = item.connector_mandate_details.and_then(|details| { + details.payments.map(|payments| { + payments.values().any(|connector_token_reference| { + connector_token_reference.connector_token_status + == api_enums::ConnectorTokenStatus::Active + }) + }) + }); + Ok(Self { id: item.id, customer_id: item.customer_id, @@ -999,6 +1008,7 @@ impl transformers::ForeignTryFrom<domain::PaymentMethod> for api::CustomerPaymen is_default: false, billing: payment_method_billing, network_tokenization: network_token_resp, + psp_tokenization_enabled: psp_tokenization_enabled.unwrap_or(false), }) } }
2025-03-13T11:04:43Z
## 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 --> Added `psp_tokenization_enabled` field to `CustomerPaymentMethod` that denotes whether `psp_tokenization` is enabled for a saved payment method ### 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 #7518 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create a Payment Method Session NOTE: `psp_tokenization` field is required to generate token (Set `psp_tokenization_enabled` to `true`). Its value can either be `multi_use` or `single_use`. ``` curl --location 'http://localhost:8080/v2/payment-methods-session' \ --header 'x-profile-id: pro_piGRXWnlda2RVykbLnUU' \ --header 'Authorization: api-key=dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' \ --data-raw '{ "customer_id": "12345_cus_0195ae660fb270e28ea754519806b702", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "psp_tokenization": { "tokenization_type": "multi_use" } }' ``` - Confirm the Payment Method Session ``` curl --location 'http://localhost:8080/v2/payment-methods-session/12345_pms_0195ae661bbc7d60a35f95ab5d29fe52/confirm' \ --header 'x-profile-id: pro_piGRXWnlda2RVykbLnUU' \ --header 'Authorization: publishable-key=pk_dev_04fccc9893564ead968e58bff3b8068b,client-secret=cs_0195ae661bbd70e39efd4f332f062b35' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "05", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "payment_method_type": "card", "payment_method_subtype": "credit" }' ``` Response: ```json { "id": "12345_pms_0195ae661bbc7d60a35f95ab5d29fe52", "customer_id": "12345_cus_0195ae660fb270e28ea754519806b702", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "psp_tokenization": { "tokenization_type": "multi_use", "connector_id": null }, "network_tokenization": null, "expires_at": "2025-03-19T12:49:42.237Z", "client_secret": "CLIENT_SECRET_REDACTED", "return_url": null, "next_action": null, "authentication_details": { "status": "succeeded", "error": null }, "associated_payment_methods": null } ``` - Retrieve Payment Method: ``` curl --location 'http://localhost:8080/v2/payment-methods/12345_pm_0195ae669d8476d1bdcb54a3b266b5a6' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_piGRXWnlda2RVykbLnUU' \ --header 'X-Resource-Type: payment_method' \ --header 'api-key: dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' \ --header 'Authorization: api-key=dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' ``` Response: ```json { "id": "12345_pm_0195ae669d8476d1bdcb54a3b266b5a6", "merchant_id": "cloth_seller_ofmnd07CcVEfqVvCSgAJ", "customer_id": "12345_cus_0195ae660fb270e28ea754519806b702", "payment_method_type": "card", "payment_method_subtype": "credit", "recurring_enabled": false, "created": "2025-03-19T12:35:15.461Z", "last_used_at": "2025-03-19T12:35:15.461Z", "payment_method_data": { "card": { "issuer_country": null, "last4_digits": "4242", "expiry_month": "05", "expiry_year": "25", "card_holder_name": "John Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": null, "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "connector_tokens": [ { "connector_id": "mca_8nVPkBONTcH6HgSf3u2W", "token_type": "multi_use", "status": "active", "connector_token_request_reference_id": "jRkI9KrD9ndJsl4YUi", "original_payment_authorized_amount": 0, "original_payment_authorized_currency": "USD", "metadata": null, "token": "pm_1R4Lq4D5R7gDAGffpqWfb9lx" } ], "network_token": null } ``` Customer Payment Methods List: ``` curl --location 'http://localhost:8080/v2/customers/12345_cus_0195ae660fb270e28ea754519806b702/saved-payment-methods' \ --header 'api-key: dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_piGRXWnlda2RVykbLnUU' \ --header 'Authorization: api-key=dev_m7AYHTfChsNPrDsCJodKhqKiRVwgW5dzawo2T3lHGrmkrfkesXVvI3LExORXwRcW' ``` Response: ```json { "customer_payment_methods": [ { "id": "12345_pm_0195ae669d8476d1bdcb54a3b266b5a6", "customer_id": "12345_cus_0195ae660fb270e28ea754519806b702", "payment_method_type": "card", "payment_method_subtype": "credit", "recurring_enabled": true, "payment_method_data": { "card": { "issuer_country": null, "last4_digits": "4242", "expiry_month": "05", "expiry_year": "25", "card_holder_name": "John Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": null, "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "bank": null, "created": "2025-03-19T12:35:15.461Z", "requires_cvv": true, "last_used_at": "2025-03-19T12:35:15.461Z", "is_default": false, "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "network_tokenization": null, "psp_tokenization_enabled": true } ] } ``` ## 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.113.0
f8a8d2a0300034c8e6ab36d011f9180993dc5e5f
f8a8d2a0300034c8e6ab36d011f9180993dc5e5f
juspay/hyperswitch
juspay__hyperswitch-7511
Bug: [CHORE] Update Globalpay configs with the countries and currencies that it supports The connector has been untouched for long. The connector is not supported supported everywhere. So, it is better for us to restrict it to certain countries that it supports.
diff --git a/config/config.example.toml b/config/config.example.toml index ad910ef415a..115dd4554a3 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -614,6 +614,14 @@ direct_carrier_billing = {country = "MA, CM, ZA, EG, SN, DZ, TN, ML, GN, GH, LY, credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [pm_filters.klarna] klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 47b65efabc4..a6e531b2aa6 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -322,6 +322,14 @@ debit.currency = "USD" credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [pm_filters.globepay] ali_pay.currency = "GBP,CNY" we_chat_pay.currency = "GBP,CNY" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index fc4bca222a9..959d2bf7fe9 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -372,6 +372,14 @@ debit.currency = "USD" credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC"} +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC"} +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [pm_filters.globepay] ali_pay.currency = "GBP,CNY" we_chat_pay.currency = "GBP,CNY" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 37346fc3467..e919a0fa566 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -374,6 +374,14 @@ debit.currency = "USD" credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC"} +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [pm_filters.globepay] ali_pay.currency = "GBP,CNY" we_chat_pay.currency = "GBP,CNY" diff --git a/config/development.toml b/config/development.toml index eab89187a46..57e0ebef051 100644 --- a/config/development.toml +++ b/config/development.toml @@ -587,6 +587,14 @@ paypal = { currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,N credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [pm_filters.jpmorgan] debit = { country = "CA, GB, US, AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IE, IT, LV, LT, LU, MT, NL, PL, PT, RO, SK, SI, ES, SE", currency = "USD, EUR, GBP, AUD, NZD, SGD, CAD, JPY, HKD, KRW, TWD, MXN, BRL, DKK, NOK, ZAR, SEK, CHF, CZK, PLN, TRY, AFN, ALL, DZD, AOA, ARS, AMD, AWG, AZN, BSD, BDT, BBD, BYN, BZD, BMD, BOB, BAM, BWP, BND, BGN, BIF, BTN, XOF, XAF, XPF, KHR, CVE, KYD, CLP, CNY, COP, KMF, CDF, CRC, HRK, DJF, DOP, XCD, EGP, ETB, FKP, FJD, GMD, GEL, GHS, GIP, GTQ, GYD, HTG, HNL, HUF, ISK, INR, IDR, ILS, JMD, KZT, KES, LAK, LBP, LSL, LRD, MOP, MKD, MGA, MWK, MYR, MVR, MRU, MUR, MDL, MNT, MAD, MZN, MMK, NAD, NPR, ANG, PGK, NIO, NGN, PKR, PAB, PYG, PEN, PHP, QAR, RON, RWF, SHP, WST, STN, SAR, RSD, SCR, SLL, SBD, SOS, LKR, SRD, SZL, TJS, TZS, THB, TOP, TTD, UGX, UAH, AED, UYU, UZS, VUV, VND, YER, ZMW" } credit = { country = "CA, GB, US, AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IE, IT, LV, LT, LU, MT, NL, PL, PT, RO, SK, SI, ES, SE", currency = "USD, EUR, GBP, AUD, NZD, SGD, CAD, JPY, HKD, KRW, TWD, MXN, BRL, DKK, NOK, ZAR, SEK, CHF, CZK, PLN, TRY, AFN, ALL, DZD, AOA, ARS, AMD, AWG, AZN, BSD, BDT, BBD, BYN, BZD, BMD, BOB, BAM, BWP, BND, BGN, BIF, BTN, XOF, XAF, XPF, KHR, CVE, KYD, CLP, CNY, COP, KMF, CDF, CRC, HRK, DJF, DOP, XCD, EGP, ETB, FKP, FJD, GMD, GEL, GHS, GIP, GTQ, GYD, HTG, HNL, HUF, ISK, INR, IDR, ILS, JMD, KZT, KES, LAK, LBP, LSL, LRD, MOP, MKD, MGA, MWK, MYR, MVR, MRU, MUR, MDL, MNT, MAD, MZN, MMK, NAD, NPR, ANG, PGK, NIO, NGN, PKR, PAB, PYG, PEN, PHP, QAR, RON, RWF, SHP, WST, STN, SAR, RSD, SCR, SLL, SBD, SOS, LKR, SRD, SZL, TJS, TZS, THB, TOP, TTD, UGX, UAH, AED, UYU, UZS, VUV, VND, YER, ZMW" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 9a24adcd5e9..8982fbb5bd4 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -557,6 +557,14 @@ paypal = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,B credit = { country = "US, CA", currency = "USD, CAD" } debit = { country = "US, CA", currency = "USD, CAD" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [pm_filters.klarna] klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 296bdbd9ddc..ef291f169c1 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -501,10 +501,12 @@ pub enum Currency { CAD, CDF, CHF, + CLF, CLP, CNY, COP, CRC, + CUC, CUP, CVE, CZK, @@ -600,6 +602,7 @@ pub enum Currency { SOS, SRD, SSP, + STD, STN, SVC, SYP, @@ -711,9 +714,11 @@ impl Currency { Self::CAD => "124", Self::CDF => "976", Self::CHF => "756", + Self::CLF => "990", Self::CLP => "152", Self::COP => "170", Self::CRC => "188", + Self::CUC => "931", Self::CUP => "192", Self::CVE => "132", Self::CZK => "203", @@ -810,6 +815,7 @@ impl Currency { Self::SOS => "706", Self::SRD => "968", Self::SSP => "728", + Self::STD => "678", Self::STN => "930", Self::SVC => "222", Self::SYP => "760", @@ -889,9 +895,11 @@ impl Currency { | Self::CAD | Self::CDF | Self::CHF + | Self::CLF | Self::CNY | Self::COP | Self::CRC + | Self::CUC | Self::CUP | Self::CVE | Self::CZK @@ -978,6 +986,7 @@ impl Currency { | Self::SOS | Self::SRD | Self::SSP + | Self::STD | Self::STN | Self::SVC | Self::SYP @@ -1037,10 +1046,12 @@ impl Currency { | Self::CAD | Self::CDF | Self::CHF + | Self::CLF | Self::CLP | Self::CNY | Self::COP | Self::CRC + | Self::CUC | Self::CUP | Self::CVE | Self::CZK @@ -1131,6 +1142,7 @@ impl Currency { | Self::SOS | Self::SRD | Self::SSP + | Self::STD | Self::STN | Self::SVC | Self::SYP @@ -1163,11 +1175,178 @@ impl Currency { } } + pub fn is_four_decimal_currency(self) -> bool { + match self { + Self::CLF => true, + Self::AED + | Self::AFN + | Self::ALL + | Self::AMD + | Self::AOA + | Self::ANG + | Self::ARS + | Self::AUD + | Self::AWG + | Self::AZN + | Self::BAM + | Self::BBD + | Self::BDT + | Self::BGN + | Self::BHD + | Self::BIF + | Self::BMD + | Self::BND + | Self::BOB + | Self::BRL + | Self::BSD + | Self::BTN + | Self::BWP + | Self::BYN + | Self::BZD + | Self::CAD + | Self::CDF + | Self::CHF + | Self::CLP + | Self::CNY + | Self::COP + | Self::CRC + | Self::CUC + | Self::CUP + | Self::CVE + | Self::CZK + | Self::DJF + | Self::DKK + | Self::DOP + | Self::DZD + | Self::EGP + | Self::ERN + | Self::ETB + | Self::EUR + | Self::FJD + | Self::FKP + | Self::GBP + | Self::GEL + | Self::GHS + | Self::GIP + | Self::GMD + | Self::GNF + | Self::GTQ + | Self::GYD + | Self::HKD + | Self::HNL + | Self::HRK + | Self::HTG + | Self::HUF + | Self::IDR + | Self::ILS + | Self::INR + | Self::IQD + | Self::IRR + | Self::ISK + | Self::JMD + | Self::JOD + | Self::JPY + | Self::KES + | Self::KGS + | Self::KHR + | Self::KMF + | Self::KPW + | Self::KRW + | Self::KWD + | Self::KYD + | Self::KZT + | Self::LAK + | Self::LBP + | Self::LKR + | Self::LRD + | Self::LSL + | Self::LYD + | Self::MAD + | Self::MDL + | Self::MGA + | Self::MKD + | Self::MMK + | Self::MNT + | Self::MOP + | Self::MRU + | Self::MUR + | Self::MVR + | Self::MWK + | Self::MXN + | Self::MYR + | Self::MZN + | Self::NAD + | Self::NGN + | Self::NIO + | Self::NOK + | Self::NPR + | Self::NZD + | Self::OMR + | Self::PAB + | Self::PEN + | Self::PGK + | Self::PHP + | Self::PKR + | Self::PLN + | Self::PYG + | Self::QAR + | Self::RON + | Self::RSD + | Self::RUB + | Self::RWF + | Self::SAR + | Self::SBD + | Self::SCR + | Self::SDG + | Self::SEK + | Self::SGD + | Self::SHP + | Self::SLE + | Self::SLL + | Self::SOS + | Self::SRD + | Self::SSP + | Self::STD + | Self::STN + | Self::SVC + | Self::SYP + | Self::SZL + | Self::THB + | Self::TJS + | Self::TMT + | Self::TND + | Self::TOP + | Self::TRY + | Self::TTD + | Self::TWD + | Self::TZS + | Self::UAH + | Self::UGX + | Self::USD + | Self::UYU + | Self::UZS + | Self::VES + | Self::VND + | Self::VUV + | Self::WST + | Self::XAF + | Self::XCD + | Self::XPF + | Self::XOF + | Self::YER + | Self::ZAR + | Self::ZMW + | Self::ZWL => false, + } + } + pub fn number_of_digits_after_decimal_point(self) -> u8 { if self.is_zero_decimal_currency() { 0 } else if self.is_three_decimal_currency() { 3 + } else if self.is_four_decimal_currency() { + 4 } else { 2 } diff --git a/crates/currency_conversion/src/types.rs b/crates/currency_conversion/src/types.rs index 2001495b2db..587c36ffe6c 100644 --- a/crates/currency_conversion/src/types.rs +++ b/crates/currency_conversion/src/types.rs @@ -105,10 +105,12 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::CAD => iso::CAD, Currency::CDF => iso::CDF, Currency::CHF => iso::CHF, + Currency::CLF => iso::CLF, Currency::CLP => iso::CLP, Currency::CNY => iso::CNY, Currency::COP => iso::COP, Currency::CRC => iso::CRC, + Currency::CUC => iso::CUC, Currency::CUP => iso::CUP, Currency::CVE => iso::CVE, Currency::CZK => iso::CZK, @@ -204,6 +206,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::SOS => iso::SOS, Currency::SRD => iso::SRD, Currency::SSP => iso::SSP, + Currency::STD => iso::STD, Currency::STN => iso::STN, Currency::SVC => iso::SVC, Currency::SYP => iso::SYP, diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 0479753d8d0..94faa4847df 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -370,10 +370,12 @@ impl IntoDirValue for api_enums::Currency { Self::CAD => Ok(dirval!(PaymentCurrency = CAD)), Self::CDF => Ok(dirval!(PaymentCurrency = CDF)), Self::CHF => Ok(dirval!(PaymentCurrency = CHF)), + Self::CLF => Ok(dirval!(PaymentCurrency = CLF)), Self::CLP => Ok(dirval!(PaymentCurrency = CLP)), Self::CNY => Ok(dirval!(PaymentCurrency = CNY)), Self::COP => Ok(dirval!(PaymentCurrency = COP)), Self::CRC => Ok(dirval!(PaymentCurrency = CRC)), + Self::CUC => Ok(dirval!(PaymentCurrency = CUC)), Self::CUP => Ok(dirval!(PaymentCurrency = CUP)), Self::CVE => Ok(dirval!(PaymentCurrency = CVE)), Self::CZK => Ok(dirval!(PaymentCurrency = CZK)), @@ -469,6 +471,7 @@ impl IntoDirValue for api_enums::Currency { Self::SOS => Ok(dirval!(PaymentCurrency = SOS)), Self::SRD => Ok(dirval!(PaymentCurrency = SRD)), Self::SSP => Ok(dirval!(PaymentCurrency = SSP)), + Self::STD => Ok(dirval!(PaymentCurrency = STD)), Self::STN => Ok(dirval!(PaymentCurrency = STN)), Self::SVC => Ok(dirval!(PaymentCurrency = SVC)), Self::SYP => Ok(dirval!(PaymentCurrency = SYP)), diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index bdf46a8ee40..edc62676154 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -342,6 +342,14 @@ pix = { country = "BR", currency = "BRL" } red_compra = { country = "CL", currency = "CLP" } red_pagos = { country = "UY", currency = "UYU" } +[pm_filters.globalpay] +credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } +eps = { country = "AT", currency = "EUR" } +giropay = { country = "DE", currency = "EUR" } +ideal = { country = "NL", currency = "EUR" } +sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } + [pm_filters.rapyd] apple_pay = { country = "AL,AS,AD,AR,AM,AU,AT,AZ,BH,BE,BM,BA,BR,BG,CA,KH,KY,CL,CO,CR,HR,CY,CZ,DK,DO,EC,SV,EE,FO,FI,FR,GE,DE,GI,GR,GL,GU,GT,GG,HN,HK,HU,IS,IE,IM,IL,IT,JP,KZ,KG,KW,LV,LI,LT,LU,MO,MY,MT,MX,MD,MC,ME,MA,NL,NZ,NI,MK,MP,NO,PA,PY,PR,PE,PL,PT,QA,RO,SM,RS,SG,SK,SI,ZA,ES,SE,CH,TW,TJ,TH,UA,AE,GB,US,UY,VI,VN", currency = "EUR,GBP,ISK,USD" } google_pay = { country = "AM,AT,AU,AZ,BA,BE,BG,BY,CA,CH,CL,CN,CO,CR,CY,CZ,DE,DK,DO,EC,EE,EG,ES,FI,FR,GB,GE,GL,GR,GT,HK,HN,HR,HU,IE,IL,IM,IS,IT,JE,JP,JO,KZ,KW,LA,LI,LT,LU,LV,MA,MC,MD,ME,MO,MN,MT,MX,MY,NC,NL,NO,NZ,OM,PA,PE,PL,PR,PT,QA,RO,RS,SA,SE,SG,SI,SK,SM,SV,TH,TW,UA,US,UY,VA,VN,ZA", currency = "EUR,GBP,ISK,USD" }
2025-03-13T07:57:41Z
## 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 adds necessary payment method configs to the GlobalPay connector. For wallets (Paypal, Apple Pay and Google Pay), their developer docs does not mention about them being support while their main page says it to be supported. Have got in touch with the team asking for clarification on this topic. Will update the wallet configs accordingly in upcoming PRs. ### 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` --> config 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 https://github.com/juspay/hyperswitch/issues/7511 Refer to the parent issue of the attached issue to learn more about supported currencies and countries. Supported payment types: https://github.com/juspay/hyperswitch/issues/7502#issuecomment-2718463863 ## 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 via GlobalPay should fail if currencies or countries that are not supported is used to make transactions: ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_fO6IOJVOk6dmWoDhkHnw3EzJHjZytuOfViMDKpi1eOasWTqrXIcUuuoGNUDafqGZ' \ --data-raw '{ "amount": 1000, "currency": "XPS", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4263970000005262", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "PiX" } } }' ``` ```json { "error": { "error_type": "invalid_request", "message": "Json deserialize error: unknown variant `XPS`, expected one of `AED`, `AFN`, `ALL`, `AMD`, `ANG`, `AOA`, `ARS`, `AUD`, `AWG`, `AZN`, `BAM`, `BBD`, `BDT`, `BGN`, `BHD`, `BIF`, `BMD`, `BND`, `BOB`, `BRL`, `BSD`, `BTN`, `BWP`, `BYN`, `BZD`, `CAD`, `CDF`, `CHF`, `CLF`, `CLP`, `CNY`, `COP`, `CRC`, `CUC`, `CUP`, `CVE`, `CZK`, `DJF`, `DKK`, `DOP`, `DZD`, `EGP`, `ERN`, `ETB`, `EUR`, `FJD`, `FKP`, `GBP`, `GEL`, `GHS`, `GIP`, `GMD`, `GNF`, `GTQ`, `GYD`, `HKD`, `HNL`, `HRK`, `HTG`, `HUF`, `IDR`, `ILS`, `INR`, `IQD`, `IRR`, `ISK`, `JMD`, `JOD`, `JPY`, `KES`, `KGS`, `KHR`, `KMF`, `KPW`, `KRW`, `KWD`, `KYD`, `KZT`, `LAK`, `LBP`, `LKR`, `LRD`, `LSL`, `LYD`, `MAD`, `MDL`, `MGA`, `MKD`, `MMK`, `MNT`, `MOP`, `MRU`, `MUR`, `MVR`, `MWK`, `MXN`, `MYR`, `MZN`, `NAD`, `NGN`, `NIO`, `NOK`, `NPR`, `NZD`, `OMR`, `PAB`, `PEN`, `PGK`, `PHP`, `PKR`, `PLN`, `PYG`, `QAR`, `RON`, `RSD`, `RUB`, `RWF`, `SAR`, `SBD`, `SCR`, `SDG`, `SEK`, `SGD`, `SHP`, `SLE`, `SLL`, `SOS`, `SRD`, `SSP`, `STD`, `STN`, `SVC`, `SYP`, `SZL`, `THB`, `TJS`, `TMT`, `TND`, `TOP`, `TRY`, `TTD`, `TWD`, `TZS`, `UAH`, `UGX`, `USD`, `UYU`, `UZS`, `VES`, `VND`, `VUV`, `WST`, `XAF`, `XCD`, `XOF`, `XPF`, `YER`, `ZAR`, `ZMW`, `ZWL` at line 3 column 19", "code": "IR_06" } } ``` bank redirect: ```curl curl --location 'http://Localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_fO6IOJVOk6dmWoDhkHnw3EzJHjZytuOfViMDKpi1eOasWTqrXIcUuuoGNUDafqGZ' \ --data-raw '{ "amount": 1000, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_data": { "bank_redirect": { "ideal": { "bank_name": "ing" } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "PiX" } } }' ``` ```json { "error": { "type": "invalid_request", "message": "No eligible connector was found for the current payment method configuration", "code": "IR_39" } } ``` without this change, the payment would fail and the connector would throw `INVALID_REQUEST_DATA` ## 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.113.0
13c621ae62cda8f03ebd3958825b28a66b885234
13c621ae62cda8f03ebd3958825b28a66b885234
juspay/hyperswitch
juspay__hyperswitch-7510
Bug: [FEATURE] add functionality to enable payment link form button only when form is filled ### Feature Description Payment link renders a submit button for submitting the payment form data. This button is always enabled, and displays any errors in case an incomplete form was tried to submit. This feature takes care of enabling the button only when the form is complete. ### Possible Implementation Since payment link already has a defined behavior today - to keep the button enabled, but display validation errors in case an incomplete form was submitted, this new feature can be added behind a payment link config flag. `enable_button_only_on_form_ready` - default will be false This will control the behavior of enabling / disabling for incomplete forms. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index d93208fb665..1ffd5a880b5 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -11583,6 +11583,14 @@ "type": "object", "description": "Metadata is useful for storing additional, unstructured information about the merchant account.", "nullable": true + }, + "product_type": { + "allOf": [ + { + "$ref": "#/components/schemas/api_enums.MerchantProductType" + } + ], + "nullable": true } }, "additionalProperties": false @@ -11717,6 +11725,14 @@ }, "recon_status": { "$ref": "#/components/schemas/ReconStatus" + }, + "product_type": { + "allOf": [ + { + "$ref": "#/components/schemas/api_enums.MerchantProductType" + } + ], + "nullable": true } } }, @@ -14036,7 +14052,8 @@ "display_sdk_only", "enabled_saved_payment_method", "hide_card_nickname_field", - "show_card_form_by_default" + "show_card_form_by_default", + "enable_button_only_on_form_ready" ], "properties": { "theme": { @@ -14160,6 +14177,10 @@ } }, "nullable": true + }, + "enable_button_only_on_form_ready": { + "type": "boolean", + "description": "Flag to enable the button only when the payment form is ready for submission" } } }, @@ -14297,6 +14318,11 @@ } }, "nullable": true + }, + "enable_button_only_on_form_ready": { + "type": "boolean", + "description": "Flag to enable the button only when the payment form is ready for submission", + "nullable": true } } }, diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index c2fe52010f0..f007d5ebdd2 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -13921,6 +13921,14 @@ } ], "nullable": true + }, + "product_type": { + "allOf": [ + { + "$ref": "#/components/schemas/api_enums.MerchantProductType" + } + ], + "nullable": true } }, "additionalProperties": false @@ -14154,6 +14162,14 @@ } ], "nullable": true + }, + "product_type": { + "allOf": [ + { + "$ref": "#/components/schemas/api_enums.MerchantProductType" + } + ], + "nullable": true } } }, @@ -16580,7 +16596,8 @@ "display_sdk_only", "enabled_saved_payment_method", "hide_card_nickname_field", - "show_card_form_by_default" + "show_card_form_by_default", + "enable_button_only_on_form_ready" ], "properties": { "theme": { @@ -16704,6 +16721,10 @@ } }, "nullable": true + }, + "enable_button_only_on_form_ready": { + "type": "boolean", + "description": "Flag to enable the button only when the payment form is ready for submission" } } }, @@ -16841,6 +16862,11 @@ } }, "nullable": true + }, + "enable_button_only_on_form_ready": { + "type": "boolean", + "description": "Flag to enable the button only when the payment form is ready for submission", + "nullable": true } } }, diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 61bb7c009e3..b6f1e0a8b96 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2839,6 +2839,8 @@ pub struct PaymentLinkConfigRequest { pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + /// Flag to enable the button only when the payment form is ready for submission + pub enable_button_only_on_form_ready: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] @@ -2924,6 +2926,8 @@ pub struct PaymentLinkConfig { pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + /// Flag to enable the button only when the payment form is ready for submission + pub enable_button_only_on_form_ready: bool, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index f9540fd08fc..8f5e5fc8b48 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -7883,6 +7883,7 @@ pub struct PaymentLinkDetails { pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] @@ -7900,6 +7901,7 @@ pub struct SecurePaymentLinkDetails { pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 9d47ed7b594..384f7c7df24 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -653,6 +653,7 @@ pub struct PaymentLinkConfigRequest { pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, + pub enable_button_only_on_form_ready: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index e51d8daa791..4f2f4c49ea1 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -193,6 +193,8 @@ pub struct PaymentLinkConfigRequestForPayments { /// Payment link configuration rules pub payment_link_ui_rules: Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, + /// Flag to enable the button only when the payment form is ready for submission + pub enable_button_only_on_form_ready: Option<bool>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments); diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index fac251d8b68..65372d9f053 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -417,6 +417,7 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> payment_button_text_colour: item.payment_button_text_colour, sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, + enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, } } fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest { @@ -440,6 +441,7 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, + enable_button_only_on_form_ready, } = self; api_models::admin::PaymentLinkConfigRequest { theme, @@ -467,6 +469,7 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, + enable_button_only_on_form_ready, } } } diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 57ec34227b0..247693864da 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -158,6 +158,9 @@ pub const DEFAULT_DISPLAY_SDK_ONLY: bool = false; /// Default bool to enable saved payment method pub const DEFAULT_ENABLE_SAVED_PAYMENT_METHOD: bool = false; +/// [PaymentLink] Default bool for enabling button only when form is ready +pub const DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY: bool = false; + /// Default Merchant Logo Link pub const DEFAULT_MERCHANT_LOGO: &str = "https://live.hyperswitch.io/payment-link-assets/Merchant_placeholder.png"; diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index 292f582df9a..c13e087947b 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -23,8 +23,9 @@ use super::{ use crate::{ consts::{ self, DEFAULT_ALLOWED_DOMAINS, DEFAULT_BACKGROUND_COLOR, DEFAULT_DISPLAY_SDK_ONLY, - DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, DEFAULT_HIDE_CARD_NICKNAME_FIELD, - DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG, DEFAULT_SDK_LAYOUT, DEFAULT_SHOW_CARD_FORM, + DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, + DEFAULT_HIDE_CARD_NICKNAME_FIELD, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG, + DEFAULT_SDK_LAYOUT, DEFAULT_SHOW_CARD_FORM, }, errors::RouterResponse, get_payment_link_config_value, get_payment_link_config_value_based_on_priority, @@ -137,6 +138,7 @@ pub async fn form_payment_link_data( payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, + enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, } }; @@ -290,6 +292,7 @@ pub async fn form_payment_link_data( payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(), sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(), payment_link_ui_rules: payment_link_config.payment_link_ui_rules.clone(), + enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready, }; Ok(( @@ -348,6 +351,8 @@ pub async fn initiate_secure_payment_link_flow( payment_button_text_colour: payment_link_config.payment_button_text_colour, sdk_ui_rules: payment_link_config.sdk_ui_rules, payment_link_ui_rules: payment_link_config.payment_link_ui_rules, + enable_button_only_on_form_ready: payment_link_config + .enable_button_only_on_form_ready, }; let js_script = format!( "window.__PAYMENT_DETAILS = {}", @@ -634,6 +639,7 @@ pub fn get_payment_link_config_based_on_priority( enabled_saved_payment_method, hide_card_nickname_field, show_card_form_by_default, + enable_button_only_on_form_ready, ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, @@ -647,7 +653,11 @@ pub fn get_payment_link_config_based_on_priority( DEFAULT_ENABLE_SAVED_PAYMENT_METHOD ), (hide_card_nickname_field, DEFAULT_HIDE_CARD_NICKNAME_FIELD), - (show_card_form_by_default, DEFAULT_SHOW_CARD_FORM) + (show_card_form_by_default, DEFAULT_SHOW_CARD_FORM), + ( + enable_button_only_on_form_ready, + DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY + ) ); let ( @@ -702,6 +712,7 @@ pub fn get_payment_link_config_based_on_priority( payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, + enable_button_only_on_form_ready, }; Ok((payment_link_config, domain_name)) @@ -812,6 +823,7 @@ pub async fn get_payment_link_status( payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, + enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, } }; diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css index 7b347306809..f58617261d6 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css @@ -652,6 +652,10 @@ body { cursor: not-allowed; } +#submit.not-ready { + background-color: #C2C2C2 !important; +} + #submit-spinner { width: 28px; height: 28px; diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html index 9abcc440068..ac04479e44c 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html @@ -290,9 +290,9 @@ <div></div> </div> </div> - <form id="payment-form" onclick="handleSubmit(); return false;"> + <form id="payment-form"> <div id="unified-checkout"></div> - <button id="submit" class="hidden"> + <button type="submit" id="submit" class="hidden"> <span id="submit-spinner" class="hidden"></span> <span id="submit-button-text"></span> </button> diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js index 5b8267c57a9..e73e23076a9 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js @@ -257,7 +257,7 @@ function boot() { // Update payment link styles var paymentLinkUiRules = paymentDetails.payment_link_ui_rules; - if (paymentLinkUiRules !== null && typeof paymentLinkUiRules === "object" && Object.getPrototypeOf(paymentLinkUiRules) === Object.prototype) { + if (isObject(paymentLinkUiRules)) { updatePaymentLinkUi(paymentLinkUiRules); } @@ -279,7 +279,18 @@ function boot() { boot(); /** - * Use - add event listeners for changing UI on screen resize + * Use - checks if a given value is an object + * @param {any} val + * @returns {boolean} + */ +function isObject(val) { + return val !== null && typeof val === "object" && Object.getPrototypeOf(val) === Object.prototype +} + +/** + * Use - add event listeners for changing UI on + * - Screen resize + * - Form inputs * @param {PaymentDetails} paymentDetails */ function initializeEventListeners(paymentDetails) { @@ -384,17 +395,58 @@ function initializeEventListeners(paymentDetails) { // @ts-ignore window.state.isMobileView = currentWidth <= 1199; }); + + var paymentForm = document.getElementById("payment-form"); + if (paymentForm instanceof HTMLFormElement) { + paymentForm.addEventListener("submit", function (event) { + event.preventDefault(); + handleSubmit(event); + }) + } + + if (paymentDetails.enable_button_only_on_form_ready) { + handleFormReadyForSubmission(); + } +} + +function handleFormReadyForSubmission() { + window.addEventListener("message", function (event) { + // Event listener for updating the button rules + if (isObject(event.data) && event.data["isFormReadyForSubmission"] !== null) { + let isFormReadyForSubmission = event.data["isFormReadyForSubmission"]; + var submitButtonNode = document.getElementById("submit"); + if (submitButtonNode instanceof HTMLButtonElement) { + if (isFormReadyForSubmission === false) { + submitButtonNode.disabled = true; + addClass("#submit", "not-ready"); + addClass("#submit", "disabled"); + } else if (isFormReadyForSubmission === true) { + submitButtonNode.disabled = false; + removeClass("#submit", "not-ready"); + removeClass("#submit", "disabled"); + } + } + } + }); } /** * Trigger - post mounting SDK * Use - set relevant classes to elements in the doc for showing SDK **/ -function showSDK(display_sdk_only) { +function showSDK(display_sdk_only, enable_button_only_on_form_ready) { if (!display_sdk_only) { show("#hyper-checkout-details"); } show("#hyper-checkout-sdk"); + if (enable_button_only_on_form_ready) { + addClass("#submit", "not-ready"); + addClass("#submit", "disabled"); + var submitButtonNode = document.getElementById("submit"); + if (submitButtonNode instanceof HTMLButtonElement) { + submitButtonNode.disabled = true; + } + } show("#submit"); show("#unified-checkout"); hide("#sdk-spinner"); @@ -426,10 +478,11 @@ function handleSubmit(e) { // Update button loader hide("#submit-button-text"); show("#submit-spinner"); + addClass("#submit", "processing"); + addClass("#submit", "disabled"); var submitButtonNode = document.getElementById("submit"); if (submitButtonNode instanceof HTMLButtonElement) { submitButtonNode.disabled = true; - submitButtonNode.classList.add("disabled"); } hyper @@ -472,11 +525,12 @@ function handleSubmit(e) { console.error("Error confirming payment_intent", error); }) .finally(() => { + removeClass("#submit", "processing"); hide("#submit-spinner"); show("#submit-button-text"); + removeClass("#submit", "disabled"); if (submitButtonNode instanceof HTMLButtonElement) { submitButtonNode.disabled = false; - submitButtonNode.classList.remove("disabled"); } }); } diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js index ca6a944baaa..f9b0fe892cf 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js @@ -75,7 +75,7 @@ function initializeSDK() { // @ts-ignore mountUnifiedCheckout("#unified-checkout"); // @ts-ignore - showSDK(paymentDetails.display_sdk_only); + showSDK(paymentDetails.display_sdk_only, paymentDetails.enable_button_only_on_form_ready); let shimmer = document.getElementById("payment-details-shimmer"); shimmer.classList.add("reduce-opacity"); diff --git a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js index 9b5a144d29a..12ae76a2085 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js @@ -98,7 +98,7 @@ if (!isFramed) { // @ts-ignore mountUnifiedCheckout("#unified-checkout"); // @ts-ignore - showSDK(paymentDetails.display_sdk_only); + showSDK(paymentDetails.display_sdk_only, paymentDetails.enable_button_only_on_form_ready); let shimmer = document.getElementById("payment-details-shimmer"); shimmer.classList.add("reduce-opacity"); diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index a34c137dbda..d6bb8f9bf0c 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -4492,6 +4492,7 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> payment_button_text_colour: config.payment_button_text_colour, sdk_ui_rules: config.sdk_ui_rules, payment_link_ui_rules: config.payment_link_ui_rules, + enable_button_only_on_form_ready: config.enable_button_only_on_form_ready, } } } @@ -4562,6 +4563,7 @@ impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments> payment_button_text_colour: config.payment_button_text_colour, sdk_ui_rules: config.sdk_ui_rules, payment_link_ui_rules: config.payment_link_ui_rules, + enable_button_only_on_form_ready: config.enable_button_only_on_form_ready, } } } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 5baf491cb33..f2f48a26f19 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -2174,6 +2174,7 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> payment_button_text_colour: item.payment_button_text_colour, sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, + enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, } } } @@ -2204,6 +2205,7 @@ impl ForeignFrom<diesel_models::business_profile::PaymentLinkConfigRequest> payment_button_text_colour: item.payment_button_text_colour, sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, + enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, } } }
2025-03-13T08:48:56Z
## 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 adds a payment link config for controlling the behavior or Submit button on payment links (`enable_button_only_on_form_ready`) - If `enable_button_only_on_form_ready` is true - disallow incomplete form submission - [DEFAULT and CURRENT] If false - allow incomplete form submission and throw validation errors ### 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 This helps add more granular control of the payment links UX. ## How did you test it? Locally using local SDK changes <details> <summary>1. Update business profile to enable confirm button only when form is ready for submission</summary> cURL curl --location --request POST 'http://localhost:8080/account/merchant_1741692513/business_profile/pro_0pSrloAVzi0xbnpnP0mY' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{"is_connector_agnostic_mit_enabled":true,"is_network_tokenization_enabled":true,"payment_link_config":{"allowed_domains":["*"],"custom_message_for_card_terms":"Hello","enabled_saved_payment_method":true,"theme":"#1A1A1A","logo":"https://hyperswitch.io/favicon.ico","payment_button_text":"Proceed to Payment!","sdk_ui_rules":{".Label":{"fontWeight":"700 !important","fontSize":"13px !important","color":"#003264 !important","backgroundColor":"red !important","opacity":"1 !important"}},"branding_visibility":false,"business_specific_configs":{"style1":{"enabled_saved_payment_method":true,"theme":"#003264","logo":"https://hyperswitch.io/favicon.ico","display_sdk_only":true,"payment_button_text":"Confirmer","enable_button_only_on_form_ready":true,"custom_message_for_card_terms":"Pour vérifier votre compte, un montant de 0,00 € sera débité lorsque vous aurez cliqué sur le bouton « Confirmer »","sdk_ui_rules":{".Label":{"fontWeight":"600 !important","fontSize":"14px !important","color":"#003264 !important","opacity":"1 !important"},".Input":{"border":"1px solid #003264"},".Input::placeholder":{"fontWeight":"400","fontSize":"16px","color":"#00326480"},".TermsTextLabel":{"color":"#003264 !important","opacity":"1 !important"},".SaveWalletDetailsLabel":{"fontSize":"13px !important","color":"#003264 !important","opacity":"1 !important"},":has(> .TermsTextLabel)":{"opacity":"1 !important"},".SaveWalletDetailsLabel em":{"fontStyle":"normal"}},"payment_link_ui_rules":{"#submit":{"color":"#003264","fontWeight":"700","fontSize":"19px","padding":"25px 0","borderRadius":"5px","backgroundColor":"#FFA445"},"#hyper-checkout-sdk":{"backgroundColor":"#FFFFFF"}}},"style2":{"enabled_saved_payment_method":true,"theme":"#1A1A1A","logo":"https://hyperswitch.io/favicon.ico"},"au":{"theme":"#2167AE","enable_button_only_on_form_ready":true,"payment_button_text":"Pay now","display_sdk_only":true,"payment_link_ui_rules":{"#submit":{"height":"48px","width":"max-content","borderRadius":"50px","padding":"0 20px","marginTop":"24px"},"#submit.processing":{"paddingLeft":"50px !important","paddingRight":"50px !important"}},"sdk_ui_rules":{".Tab":{"display":"none"},".Input, .Input:focus, .Input--invalid, .Input--empty":{"border":"none","boxShadow":"none","borderRadius":"0","padding":"0 !important","paddingBottom":"4px !important"},".Input, .Input:focus, .Input--empty":{"borderBottom":"1px solid #23366F !important","color":"#23366F"},".Input--invalid":{"borderBottom":"1px solid #CB4B40 !important"},".Label":{"marginLeft":"0","color":"#2167AE","opacity":"1 !important","fontSize":"12px !important"},".Label--invalid, .Input--invalid, .Error":{"color":"#CB4B40 !important","opacity":"1 !important"},".InputLogo--empty":{"color":"#979797"},".InputLogo":{"color":"#23366F","margin":"-30px"},".InputLogo--invalid":{"color":"#CB4B40"},".OrPayUsingLabel, .SaveWalletDetailsLabel, .CheckboxLabel, .TermsTextLabel, .InfoElement":{"color":"#003264 !important","opacity":"1 !important"},".OrPayUsingLine":{"backgroundColor":"#003264"}}}}}}' Response {"merchant_id":"merchant_1741692513","profile_id":"pro_0pSrloAVzi0xbnpnP0mY","profile_name":"IN_default","return_url":"https://google.com/success","enable_payment_response_hash":true,"payment_response_hash_key":"kFqRl8UUlHycFDeV4xy9ibEW1bDKgNa7vfd2iYfzgfzc6x3grTHhCb2V2IoMc9uL","redirect_to_merchant_with_http_post":false,"webhook_details":{"webhook_version":"1.0.1","webhook_username":"random","webhook_password":"pass","webhook_url":"https://webhook.site/0728473e-e0aa-4bb6-9eea-85435cf54380","payment_created_enabled":true,"payment_succeeded_enabled":true,"payment_failed_enabled":true},"metadata":null,"routing_algorithm":null,"intent_fulfillment_time":900,"frm_routing_algorithm":null,"payout_routing_algorithm":null,"applepay_verified_domains":null,"session_expiry":900,"payment_link_config":{"domain_name":null,"theme":"#1A1A1A","logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":null,"enabled_saved_payment_method":true,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":"Proceed to Payment!","custom_message_for_card_terms":"Hello","payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".Label":{"opacity":"1 !important","fontSize":"13px !important","backgroundColor":"red !important","color":"#003264 !important","fontWeight":"700 !important"}},"payment_link_ui_rules":null,"enable_button_only_on_form_ready":null,"business_specific_configs":{"style2":{"theme":"#1A1A1A","logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":null,"enabled_saved_payment_method":true,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":null,"custom_message_for_card_terms":null,"payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":null,"payment_link_ui_rules":null,"enable_button_only_on_form_ready":null},"au":{"theme":"#2167AE","logo":null,"seller_name":null,"sdk_layout":null,"display_sdk_only":true,"enabled_saved_payment_method":null,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":"Pay now","custom_message_for_card_terms":null,"payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".Input, .Input:focus, .Input--invalid, .Input--empty":{"border":"none","padding":"0 !important","boxShadow":"none","borderRadius":"0","paddingBottom":"4px !important"},".Input--invalid":{"borderBottom":"1px solid #CB4B40 !important"},".Tab":{"display":"none"},".Input, .Input:focus, .Input--empty":{"color":"#23366F","borderBottom":"1px solid #23366F !important"},".OrPayUsingLabel, .SaveWalletDetailsLabel, .CheckboxLabel, .TermsTextLabel, .InfoElement":{"opacity":"1 !important","color":"#003264 !important"},".OrPayUsingLine":{"backgroundColor":"#003264"},".Label--invalid::after":{"color":"#CB4B40","content":"' *'"},".Label":{"opacity":"1 !important","color":"#2167AE","marginLeft":"0","fontSize":"12px !important"},".InputLogo":{"color":"#23366F","margin":"-30px"},".Label::after":{"content":"' *'","color":"#23366F"},".InputLogo--empty":{"color":"#979797"},".InputLogo--invalid":{"color":"#CB4B40"},".Label--invalid, .Input--invalid, .Error":{"opacity":"1 !important","color":"#CB4B40 !important"}},"payment_link_ui_rules":{"#submit":{"borderRadius":"50px","height":"48px","width":"max-content","padding":"0 20px","marginTop":"24px"},"#submit.processing":{"paddingLeft":"50px !important","paddingRight":"50px !important"}},"enable_button_only_on_form_ready":true},"style1":{"theme":"#003264","logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":true,"enabled_saved_payment_method":true,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":"Confirmer","custom_message_for_card_terms":"Pour vérifier votre compte, un montant de 0,00 € sera débité lorsque vous aurez cliqué sur le bouton « Confirmer »","payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".TermsTextLabel":{"opacity":"1 !important","color":"#003264 !important"},".Input":{"border":"1px solid #003264"},".Label":{"opacity":"1 !important","color":"#003264 !important","fontSize":"14px !important","fontWeight":"600 !important"},".Input::placeholder":{"color":"#00326480","fontSize":"16px","fontWeight":"400"},".SaveWalletDetailsLabel":{"fontSize":"13px !important","color":"#003264 !important","opacity":"1 !important"},":has(> .TermsTextLabel)":{"opacity":"1 !important"},".SaveWalletDetailsLabel em":{"fontStyle":"normal"}},"payment_link_ui_rules":{"#submit":{"color":"#003264","padding":"25px 0","fontSize":"19px","fontWeight":"700","borderRadius":"5px","backgroundColor":"#FFA445"},"#hyper-checkout-sdk":{"backgroundColor":"#FFFFFF"}},"enable_button_only_on_form_ready":true}},"allowed_domains":["*"],"branding_visibility":false},"authentication_connector_details":null,"use_billing_as_payment_method_billing":true,"extended_card_info_config":null,"collect_shipping_details_from_wallet_connector":false,"collect_billing_details_from_wallet_connector":false,"always_collect_shipping_details_from_wallet_connector":false,"always_collect_billing_details_from_wallet_connector":false,"is_connector_agnostic_mit_enabled":true,"payout_link_config":null,"outgoing_webhook_custom_http_headers":null,"tax_connector_id":null,"is_tax_connector_enabled":false,"is_network_tokenization_enabled":true,"is_auto_retries_enabled":false,"max_auto_retries_enabled":null,"always_request_extended_authorization":null,"is_click_to_pay_enabled":false,"authentication_product_ids":null,"card_testing_guard_config":{"card_ip_blocking_status":"disabled","card_ip_blocking_threshold":3,"guest_user_card_blocking_status":"disabled","guest_user_card_blocking_threshold":10,"customer_id_blocking_status":"disabled","customer_id_blocking_threshold":5,"card_testing_guard_expiry":3600},"is_clear_pan_retries_enabled":false,"force_3ds_challenge":false} </details> <details> <summary>2. Create payment link</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_sI7y2RBalVSE3nYh5k4Gs2WGws277uoKwu3Y7gM9y2U2dmDSVymbHUAqPt3zDsHr' \ --data-raw '{"customer_id":"cus_t0I7DMr69stOdG3QaLZP","profile_id":"pro_0pSrloAVzi0xbnpnP0mY","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":100,"currency":"USD","payment_link":true,"capture_method":"automatic","email":"[email protected]","session_expiry":100000,"return_url":"https://example.com"}' Response {"payment_id":"pay_ufjEW9U5WAea89stlSED","merchant_id":"merchant_1741692513","status":"requires_payment_method","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":null,"client_secret":"pay_ufjEW9U5WAea89stlSED_secret_eg6sZLpO9LH60crrsV0I","created":"2025-03-13T08:47:48.496Z","currency":"USD","customer_id":"cus_t0I7DMr69stOdG3QaLZP","customer":{"id":"cus_t0I7DMr69stOdG3QaLZP","name":"John Nether","email":"[email protected]","phone":"6168205362","phone_country_code":"+1"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Nether","phone":"6168205362","return_url":"https://example.com/","authentication_type":null,"statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_t0I7DMr69stOdG3QaLZP","created_at":1741855668,"expires":1741859268,"secret":"epk_3ccf7b98c7c54188ba5d9230c3bd21fe"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1741692513/pay_ufjEW9U5WAea89stlSED?locale=en","secure_link":"http://localhost:8080/payment_link/s/merchant_1741692513/pay_ufjEW9U5WAea89stlSED?locale=en","payment_link_id":"plink_fW4Nnwl7EcbrmjmOQ1pi"},"profile_id":"pro_0pSrloAVzi0xbnpnP0mY","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-03-14T12:34:28.493Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-03-13T08:47:48.504Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null} #### Things to validate 1. Confirm button is greyed out and disabled if form is incomplete <img width="611" alt="Screenshot 2025-03-13 at 2 37 23 PM" src="https://github.com/user-attachments/assets/ffb1b4f2-6c78-4f9c-9080-f74e2bf4223d" /> 2. Confirm button is enabled once form is completely filled <img width="627" alt="Screenshot 2025-03-13 at 2 37 36 PM" src="https://github.com/user-attachments/assets/d4312682-0283-481f-9dfa-de6f0b525810" /> </details> ## 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` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.113.0
13c621ae62cda8f03ebd3958825b28a66b885234
13c621ae62cda8f03ebd3958825b28a66b885234
juspay/hyperswitch
juspay__hyperswitch-7504
Bug: [FEATURE] Add new OLAP endpoint to fetch total count of payment methods of customer for given merchant id. Add total-payment-method-count api. this is olap api to fetch total count of payment method of customer of given merchant id.
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index ac44f65ee0e..77963ee90df 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -1884,6 +1884,16 @@ pub struct CustomerPaymentMethodsListResponse { pub customer_payment_methods: Vec<CustomerPaymentMethod>, } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, serde::Serialize, ToSchema)] +pub struct TotalPaymentMethodCountResponse { + /// total count of payment methods under the merchant + pub total_count: i64, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl common_utils::events::ApiEventMetric for TotalPaymentMethodCountResponse {} + #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs index d4ad52ae146..62f6f37ba52 100644 --- a/crates/diesel_models/src/query/payment_method.rs +++ b/crates/diesel_models/src/query/payment_method.rs @@ -1,23 +1,8 @@ -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_methods_v2") -))] use async_bb8_diesel::AsyncRunQueryDsl; -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_methods_v2") -))] -use diesel::Table; -use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_methods_v2") -))] -use diesel::{debug_query, pg::Pg, QueryDsl}; -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_methods_v2") -))] +use diesel::{ + associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, + QueryDsl, Table, +}; use error_stack::ResultExt; use super::generics; @@ -153,6 +138,28 @@ impl PaymentMethod { .attach_printable("Failed to get a count of payment methods") } + pub async fn get_count_by_merchant_id_status( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + status: common_enums::PaymentMethodStatus, + ) -> StorageResult<i64> { + let query = <Self as HasTable>::table().count().filter( + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::status.eq(status.to_owned())), + ); + + router_env::logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); + + generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( + query.get_result_async::<i64>(conn), + generics::db_metrics::DatabaseOperation::Count, + ) + .await + .change_context(errors::DatabaseError::Others) + .attach_printable("Failed to get a count of payment methods") + } + pub async fn find_by_customer_id_merchant_id_status( conn: &PgPooledConn, customer_id: &common_utils::id_type::CustomerId, @@ -275,4 +282,26 @@ impl PaymentMethod { ) .await } + + pub async fn get_count_by_merchant_id_status( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + status: common_enums::PaymentMethodStatus, + ) -> StorageResult<i64> { + let query = <Self as HasTable>::table().count().filter( + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::status.eq(status.to_owned())), + ); + + router_env::logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); + + generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( + query.get_result_async::<i64>(conn), + generics::db_metrics::DatabaseOperation::Count, + ) + .await + .change_context(errors::DatabaseError::Others) + .attach_printable("Failed to get a count of payment methods") + } } diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs index 762ab5bbf86..963ec83e0be 100644 --- a/crates/hyperswitch_domain_models/src/payment_methods.rs +++ b/crates/hyperswitch_domain_models/src/payment_methods.rs @@ -786,6 +786,12 @@ pub trait PaymentMethodInterface { status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError>; + async fn get_payment_method_count_by_merchant_id_status( + &self, + merchant_id: &id_type::MerchantId, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<i64, errors::StorageError>; + async fn insert_payment_method( &self, state: &keymanager::KeyManagerState, diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index f9a6f9a9eb9..08968997243 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -1308,6 +1308,20 @@ pub async fn list_saved_payment_methods_for_customer( )) } +#[cfg(all(feature = "v2", feature = "olap"))] +#[instrument(skip_all)] +pub async fn get_total_saved_payment_methods_for_merchant( + state: SessionState, + merchant_account: domain::MerchantAccount, +) -> RouterResponse<api::TotalPaymentMethodCountResponse> { + let total_payment_method_count = + get_total_payment_method_count_core(&state, &merchant_account).await?; + + Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( + total_payment_method_count, + )) +} + #[cfg(feature = "v2")] /// Container for the inputs required for the required fields struct RequiredFieldsInput { @@ -1778,6 +1792,27 @@ pub async fn list_customer_payment_method_core( Ok(response) } +#[cfg(all(feature = "v2", feature = "olap"))] +pub async fn get_total_payment_method_count_core( + state: &SessionState, + merchant_account: &domain::MerchantAccount, +) -> RouterResult<api::TotalPaymentMethodCountResponse> { + let db = &*state.store; + + let total_count = db + .get_payment_method_count_by_merchant_id_status( + merchant_account.get_id(), + common_enums::PaymentMethodStatus::Active, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to get total payment method count")?; + + let response = api::TotalPaymentMethodCountResponse { total_count }; + + Ok(response) +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn retrieve_payment_method( diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 7c2a9c7498f..d06d13a3123 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2176,6 +2176,16 @@ impl PaymentMethodInterface for KafkaStore { .await } + async fn get_payment_method_count_by_merchant_id_status( + &self, + merchant_id: &id_type::MerchantId, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<i64, errors::DataStorageError> { + self.diesel_store + .get_payment_method_count_by_merchant_id_status(merchant_id, status) + .await + } + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 7bb42134aa7..c43044fa327 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1039,6 +1039,10 @@ impl Customers { { route = route .service(web::resource("/list").route(web::get().to(customers::customers_list))) + .service( + web::resource("/total-payment-methods") + .route(web::get().to(payment_methods::get_total_payment_method_count)), + ) } #[cfg(all(feature = "oltp", feature = "v2", feature = "customer_v2"))] { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 880f400ccc4..1cc3442b74b 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -118,7 +118,8 @@ impl From<Flow> for ApiIdentifier { | Flow::ValidatePaymentMethod | Flow::ListCountriesCurrencies | Flow::DefaultPaymentMethodsSet - | Flow::PaymentMethodSave => Self::PaymentMethods, + | Flow::PaymentMethodSave + | Flow::TotalPaymentMethodCount => Self::PaymentMethods, Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth, diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index a32a0268714..92f16b6c4c7 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -624,6 +624,37 @@ pub async fn list_customer_payment_method_api( .await } +#[cfg(all(feature = "v2", feature = "olap"))] +#[instrument(skip_all, fields(flow = ?Flow::TotalPaymentMethodCount))] +pub async fn get_total_payment_method_count( + state: web::Data<AppState>, + req: HttpRequest, +) -> HttpResponse { + let flow = Flow::TotalPaymentMethodCount; + + Box::pin(api::server_wrap( + flow, + state, + &req, + (), + |state, auth: auth::AuthenticationData, _, _| { + payment_methods_routes::get_total_saved_payment_methods_for_merchant( + state, + auth.merchant_account, + ) + }, + auth::auth_type( + &auth::V2ApiKeyAuth, + &auth::JWTAuth { + permission: Permission::MerchantCustomerRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] /// Generate a form link for collecting payment methods for a customer #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))] diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index dc2d7816ffc..87475fcd89a 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -11,7 +11,7 @@ pub use api_models::payment_methods::{ PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodResponseData, PaymentMethodUpdate, PaymentMethodUpdateData, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, - TokenizedWalletValue2, + TokenizedWalletValue2, TotalPaymentMethodCountResponse, }; #[cfg(all( any(feature = "v2", feature = "v1"), diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index f287c8b7d50..26f88217e4a 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -574,6 +574,8 @@ pub enum Flow { CardsInfoUpdate, /// Cards Info migrate flow CardsInfoMigrate, + ///Total payment method count for merchant + TotalPaymentMethodCount, } /// Trait for providing generic behaviour to flow metric diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rs index 5ed5e36fb3c..4d52ad9d8d3 100644 --- a/crates/storage_impl/src/payment_method.rs +++ b/crates/storage_impl/src/payment_method.rs @@ -119,6 +119,17 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> { .await } + #[instrument(skip_all)] + async fn get_payment_method_count_by_merchant_id_status( + &self, + merchant_id: &id_type::MerchantId, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<i64, errors::StorageError> { + self.router_store + .get_payment_method_count_by_merchant_id_status(merchant_id, status) + .await + } + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] async fn insert_payment_method( @@ -496,6 +507,21 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> { }) } + #[instrument(skip_all)] + async fn get_payment_method_count_by_merchant_id_status( + &self, + merchant_id: &id_type::MerchantId, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<i64, errors::StorageError> { + let conn = pg_connection_read(self).await?; + PaymentMethod::get_count_by_merchant_id_status(&conn, merchant_id, status) + .await + .map_err(|error| { + let new_err = diesel_error_to_data_error(*error.current_context()); + error.change_context(new_err) + }) + } + #[instrument(skip_all)] async fn insert_payment_method( &self, @@ -810,6 +836,19 @@ impl PaymentMethodInterface for MockDb { i64::try_from(count).change_context(errors::StorageError::MockDbError) } + async fn get_payment_method_count_by_merchant_id_status( + &self, + merchant_id: &id_type::MerchantId, + status: common_enums::PaymentMethodStatus, + ) -> CustomResult<i64, errors::StorageError> { + let payment_methods = self.payment_methods.lock().await; + let count = payment_methods + .iter() + .filter(|pm| pm.merchant_id == *merchant_id && pm.status == status) + .count(); + i64::try_from(count).change_context(errors::StorageError::MockDbError) + } + async fn insert_payment_method( &self, _state: &KeyManagerState,
2025-03-11T11:42:51Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> add total-payment-method-count api. this is olap api to fetch total count of payment method of customer of given merchant id ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with 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)? --> req curl - ``` curl --location 'http://localhost:8080/v2/customers/total-payment-methods' \ --header 'x-profile-id: pro_i9LGtymazprJz3PG4aam' \ --header 'api-key: dev_QetiSV8rA4A92lmwb52ZJxE7BX8mnLLeQyr6CUoTh745dCfu2A33MVyXKdjKE0Ka' ``` resp - ``` { "total_count": 3 } ``` <img width="1146" alt="Screenshot 2025-03-12 at 11 08 57 AM" src="https://github.com/user-attachments/assets/635f6d97-690e-44dd-971d-5a62b261a4b9" /> verification:- <img width="1146" alt="Screenshot 2025-03-12 at 11 28 58 AM" src="https://github.com/user-attachments/assets/9702edd1-9a72-4144-adc2-d887afc48a3f" /> ## 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.113.0
9683b2a8955f876d99625cd5cf70c4bdf3836e9e
9683b2a8955f876d99625cd5cf70c4bdf3836e9e