repo
stringclasses
1 value
instance_id
stringlengths
22
24
problem_statement
stringlengths
24
24.1k
patch
stringlengths
0
1.9M
test_patch
stringclasses
1 value
created_at
stringdate
2022-11-25 05:12:07
2025-10-09 08:44:51
hints_text
stringlengths
11
235k
base_commit
stringlengths
40
40
juspay/hyperswitch
juspay__hyperswitch-2790
Bug: [BUG] Newly created business profile takes the value of `routing_algorithm` from the `merchant_account.routing_algorithm` column ### Bug Description When creating a new business profile, the value of `routing_algorithm` is taken from the merchant account's `routing_algorithm` field which may contain some stale data. ### Expected Behavior The value of the `routing_algorithm` in a newly created business profile should be a default value and not taken from anywhere. ### Actual Behavior The value of `routing_algorithm` is taken from the merchant account. ### Steps To Reproduce - ### Context For The Bug - ### Environment Integ ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 6bbe9149f4d..fe99d084223 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -124,9 +124,10 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)> .unwrap_or(merchant_account.redirect_to_merchant_with_http_post), webhook_details: webhook_details.or(merchant_account.webhook_details), metadata: request.metadata, - routing_algorithm: request - .routing_algorithm - .or(merchant_account.routing_algorithm), + routing_algorithm: Some(serde_json::json!({ + "algorithm_id": null, + "timestamp": 0 + })), intent_fulfillment_time: request .intent_fulfillment_time .map(i64::from)
2023-11-06T06:36:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR updates the code to set the value of the `business_profile.routing_algorithm` column to a default value during creation of business profile in DB. ### 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, the value of the `business_profile.routing_algorithm` field is optionally taken from the request or the merchant account, but there is no case where we want the value to be anything other than the default 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)? --> Local, compiler-guided ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ab3dac79b4f138cd1f60a9afc0635dcc137a4a05
juspay/hyperswitch
juspay__hyperswitch-2646
Bug: [FEATURE] Add custom-headers support for Rustman ### Feature Description This will open up wide range of possibility for all the developers out there to add custom headers of their wish to test out new things and what not? ### Possible Implementation Pass the headers in the form of a key-value pair in the run command itself such that it injects the value to the `pre-request script` of the collection dir such that after the completion, it should restore the file to its original form. ### 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/test_utils/README.md b/crates/test_utils/README.md index 1e92174b333..2edbc7104c2 100644 --- a/crates/test_utils/README.md +++ b/crates/test_utils/README.md @@ -28,9 +28,16 @@ Required fields: Optional fields: +- `--delay` -- To add a delay between requests in milliseconds. + - Maximum delay is 4294967295 milliseconds or 4294967.295 seconds or 71616 minutes or 1193.6 hours or 49.733 days + - Example: `--delay 1000` (for 1 second delay) - `--folder` -- To run individual folders in the collection - Use double quotes to specify folder name. If you wish to run multiple folders, separate them with a comma (`,`) - Example: `--folder "QuickStart"` or `--folder "Health check,QuickStart"` +- `--header` -- If you wish to add custom headers to the requests, you can pass them as a string + - Example: `--header "key:value"` + - If you want to pass multiple custom headers, you can pass multiple `--header` flags + - Example: `--header "key1:value1" --header "key2:value2"` - `--verbose` -- A boolean to print detailed logs (requests and responses) **Note:** Passing `--verbose` will also print the connector as well as admin API keys in the logs. So, make sure you don't push the commands with `--verbose` to any public repository. diff --git a/crates/test_utils/src/main.rs b/crates/test_utils/src/main.rs index 637122e468e..22c91e063d8 100644 --- a/crates/test_utils/src/main.rs +++ b/crates/test_utils/src/main.rs @@ -3,10 +3,10 @@ use std::process::{exit, Command}; use test_utils::newman_runner; fn main() { - let mut newman_command: Command = newman_runner::command_generate(); + let mut runner = newman_runner::generate_newman_command(); // Execute the newman command - let output = newman_command.spawn(); + let output = runner.newman_command.spawn(); let mut child = match output { Ok(child) => child, Err(err) => { @@ -16,6 +16,30 @@ fn main() { }; let status = child.wait(); + if runner.file_modified_flag { + let git_status = Command::new("git") + .args([ + "restore", + format!("{}/event.prerequest.js", runner.collection_path).as_str(), + ]) + .output(); + + match git_status { + Ok(output) => { + if output.status.success() { + let stdout_str = String::from_utf8_lossy(&output.stdout); + println!("Git command executed successfully: {stdout_str}"); + } else { + let stderr_str = String::from_utf8_lossy(&output.stderr); + eprintln!("Git command failed with error: {stderr_str}"); + } + } + Err(e) => { + eprintln!("Error running Git: {e}"); + } + } + } + let exit_code = match status { Ok(exit_status) => { if exit_status.success() { diff --git a/crates/test_utils/src/newman_runner.rs b/crates/test_utils/src/newman_runner.rs index c51556f8f25..af7fb559281 100644 --- a/crates/test_utils/src/newman_runner.rs +++ b/crates/test_utils/src/newman_runner.rs @@ -1,22 +1,34 @@ -use std::{env, process::Command}; +use std::{ + env, + fs::OpenOptions, + io::{self, Write}, + path::Path, + process::Command, +}; use clap::{arg, command, Parser}; use masking::PeekInterface; use crate::connector_auth::{ConnectorAuthType, ConnectorAuthenticationMap}; - #[derive(Parser)] #[command(version, about = "Postman collection runner using newman!", long_about = None)] struct Args { /// Admin API Key of the environment - #[arg(short, long = "admin_api_key")] + #[arg(short, long)] admin_api_key: String, /// Base URL of the Hyperswitch environment - #[arg(short, long = "base_url")] + #[arg(short, long)] base_url: String, /// Name of the connector - #[arg(short, long = "connector_name")] + #[arg(short, long)] connector_name: String, + /// Custom headers + #[arg(short = 'H', long = "header")] + custom_headers: Option<Vec<String>>, + /// Minimum delay in milliseconds to be added before sending a request + /// By default, 7 milliseconds will be the delay + #[arg(short, long, default_value_t = 7)] + delay_request: u32, /// Folder name of specific tests #[arg(short, long = "folder")] folders: Option<String>, @@ -25,6 +37,12 @@ struct Args { verbose: bool, } +pub struct ReturnArgs { + pub newman_command: Command, + pub file_modified_flag: bool, + pub collection_path: String, +} + // Just by the name of the connector, this function generates the name of the collection dir // Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-dir/stripe #[inline] @@ -32,7 +50,29 @@ fn get_path(name: impl AsRef<str>) -> String { format!("postman/collection-dir/{}", name.as_ref()) } -pub fn command_generate() -> Command { +// This function currently allows you to add only custom headers. +// In future, as we scale, this can be modified based on the need +fn insert_content<T, U>(dir: T, content_to_insert: U) -> io::Result<()> +where + T: AsRef<Path> + std::fmt::Debug, + U: AsRef<str> + std::fmt::Debug, +{ + let file_name = "event.prerequest.js"; + let file_path = dir.as_ref().join(file_name); + + // Open the file in write mode or create it if it doesn't exist + let mut file = OpenOptions::new() + .write(true) + .append(true) + .create(true) + .open(file_path)?; + + write!(file, "\n{:#?}", content_to_insert)?; + + Ok(()) +} + +pub fn generate_newman_command() -> ReturnArgs { let args = Args::parse(); let connector_name = args.connector_name; @@ -129,7 +169,10 @@ pub fn command_generate() -> Command { ]); } - newman_command.arg("--delay-request").arg("7"); // 7 milli seconds delay + newman_command.args([ + "--delay-request", + format!("{}", &args.delay_request).as_str(), + ]); newman_command.arg("--color").arg("on"); @@ -151,5 +194,24 @@ pub fn command_generate() -> Command { newman_command.arg("--verbose"); } - newman_command + let mut modified = false; + if let Some(headers) = &args.custom_headers { + for header in headers { + if let Some((key, value)) = header.split_once(':') { + let content_to_insert = + format!(r#"pm.request.headers.add({{key: "{key}", value: "{value}"}});"#); + if insert_content(&collection_path, &content_to_insert).is_ok() { + modified = true; + } + } else { + eprintln!("Invalid header format: {}", header); + } + } + } + + ReturnArgs { + newman_command, + file_modified_flag: modified, + collection_path, + } }
2023-10-18T17:58:48Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature - [x] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> Closes #2646 This PR as usual, narrows the main aim of rustman by making specific to Hyperswitch. With this, you should now be able to: - Set delay between each request sent as per your own wish while default being `7` milliseconds - Pass in custom-headers of your wish in run time ### How custom-headers works Custom headers inject the headers that you pass in command line into the `event.prerequest.js` file and sets a flag to `true`. After the collection is run, it checks the flag and depending on that, it will `git checkout HEAD -- <collection_name>/event.prerequest.js` to restore the file to same as before. We can also pass `-e environment.json` where you pass in custom headers but that requires some significant changes to be done to the collections to support that. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This will allow us to pass different headers in run-time to test new things and also allow you to set delay of your wish. You can now set the delay to `100000000000` and wait for ages to run a single test :D ## 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)? --> Command used: (Custom headers taken from #2116) Delay set to 0.5 seconds ```sh cargo run --bin test_utils -- --base_url=http://127.0.0.1:8080 --admin_api_key=test_admin --connector_name=stripe --folder "QuickStart" --header "payment_confirm_source:merchant_server" --header "another_header_key:and_its_value" --delay_request 4294967295 ``` In run-time, we can see the custom-headers being injected here: ![image](https://github.com/juspay/hyperswitch/assets/69745008/f0b35bb5-3e5d-4731-906b-d4d38c27090a) ![image](https://github.com/juspay/hyperswitch/assets/69745008/d07633f4-b5f8-499a-bb3f-efe16d41dbde) Value being stored in DB: ![image](https://github.com/juspay/hyperswitch/assets/69745008/d071621c-2723-4513-8567-913982e94749) Ran Stripe Collection: <img width="511" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/aaefe649-f782-47a9-9166-d6bec893c52c"> ## 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
cdca284b2a7a77cb22074fa8b3b380a088c10f00
juspay/hyperswitch
juspay__hyperswitch-2683
Bug: [FEATURE] Add support for tokenising bank details and fetching masked details while listing ### Feature Description Add support for tokenising the fetched bank details during list_customer_payment_method and return masked bank details ### Possible Implementation For each bank account fetched from payment_methods_table, tokenize each account and store it in redis, so that it could be fetched during /confirm ### 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/payment_methods.rs b/crates/api_models/src/payment_methods.rs index c40dffe4cf3..8710c69aa5c 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -811,10 +811,20 @@ pub struct CustomerPaymentMethod { #[schema(value_type = Option<Bank>)] pub bank_transfer: Option<payouts::Bank>, + /// Masked bank details from PM auth services + #[schema(example = json!({"mask": "0000"}))] + pub bank: Option<MaskedBankDetails>, + /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct MaskedBankDetails { + pub mask: String, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodId { pub payment_method_id: String, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 60fd3f315ea..85a0ca5f244 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -7,9 +7,10 @@ use api_models::{ admin::{self, PaymentMethodsEnabled}, enums::{self as api_enums}, payment_methods::{ - CardDetailsPaymentMethod, CardNetworkTypes, PaymentExperienceTypes, PaymentMethodsData, - RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, - ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled, + BankAccountConnectorDetails, CardDetailsPaymentMethod, CardNetworkTypes, MaskedBankDetails, + PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, + ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, + ResponsePaymentMethodsEnabled, }, payments::BankCodeResponse, surcharge_decision_configs as api_surcharge_decision_configs, @@ -2210,6 +2211,22 @@ pub async fn list_customer_payment_method( ) } + enums::PaymentMethod::BankDebit => { + // Retrieve the pm_auth connector details so that it can be tokenized + let bank_account_connector_details = get_bank_account_connector_details(&pm, key) + .await + .unwrap_or_else(|err| { + logger::error!(error=?err); + None + }); + if let Some(connector_details) = bank_account_connector_details { + let token_data = PaymentTokenData::AuthBankDebit(connector_details); + (None, None, token_data) + } else { + continue; + } + } + _ => ( None, None, @@ -2217,6 +2234,18 @@ pub async fn list_customer_payment_method( ), }; + // Retrieve the masked bank details to be sent as a response + let bank_details = if pm.payment_method == enums::PaymentMethod::BankDebit { + get_masked_bank_details(&pm, key) + .await + .unwrap_or_else(|err| { + logger::error!(error=?err); + None + }) + } else { + None + }; + //Need validation for enabled payment method ,querying MCA let pma = api::CustomerPaymentMethod { payment_token: parent_payment_method_token.to_owned(), @@ -2232,6 +2261,7 @@ pub async fn list_customer_payment_method( payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), created: Some(pm.created_at), bank_transfer: pmd, + bank: bank_details, requires_cvv, }; customer_pms.push(pma.to_owned()); @@ -2356,6 +2386,84 @@ pub async fn get_lookup_key_from_locker( Ok(resp) } +async fn get_masked_bank_details( + pm: &payment_method::PaymentMethod, + key: &[u8], +) -> errors::RouterResult<Option<MaskedBankDetails>> { + let payment_method_data = + decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) + .await + .change_context(errors::StorageError::DecryptionError) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to decrypt bank details")? + .map(|x| x.into_inner().expose()) + .map( + |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> { + v.parse_value::<PaymentMethodsData>("PaymentMethodsData") + .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize Payment Method Auth config") + }, + ) + .transpose()?; + + match payment_method_data { + Some(pmd) => match pmd { + PaymentMethodsData::Card(_) => Ok(None), + PaymentMethodsData::BankDetails(bank_details) => Ok(Some(MaskedBankDetails { + mask: bank_details.mask, + })), + }, + None => Err(errors::ApiErrorResponse::InternalServerError.into()) + .attach_printable("Unable to fetch payment method data"), + } +} + +async fn get_bank_account_connector_details( + pm: &payment_method::PaymentMethod, + key: &[u8], +) -> errors::RouterResult<Option<BankAccountConnectorDetails>> { + let payment_method_data = + decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) + .await + .change_context(errors::StorageError::DecryptionError) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to decrypt bank details")? + .map(|x| x.into_inner().expose()) + .map( + |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> { + v.parse_value::<PaymentMethodsData>("PaymentMethodsData") + .change_context(errors::StorageError::DeserializationFailed) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize Payment Method Auth config") + }, + ) + .transpose()?; + + match payment_method_data { + Some(pmd) => match pmd { + PaymentMethodsData::Card(_) => Err(errors::ApiErrorResponse::UnprocessableEntity { + message: "Card is not a valid entity".to_string(), + }) + .into_report(), + PaymentMethodsData::BankDetails(bank_details) => { + let connector_details = bank_details + .connector_details + .first() + .ok_or(errors::ApiErrorResponse::InternalServerError)?; + Ok(Some(BankAccountConnectorDetails { + connector: connector_details.connector.clone(), + account_id: connector_details.account_id.clone(), + mca_id: connector_details.mca_id.clone(), + access_token: connector_details.access_token.clone(), + })) + } + }, + None => Err(errors::ApiErrorResponse::InternalServerError.into()) + .attach_printable("Unable to fetch payment method data"), + } +} + #[cfg(feature = "payouts")] pub async fn get_lookup_key_for_payout_method( state: &routes::AppState, diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 04ef90546cf..d191890b8cd 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -315,6 +315,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentAttemptResponse, api_models::payments::CaptureResponse, api_models::payment_methods::RequiredFieldInfo, + api_models::payment_methods::MaskedBankDetails, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, api_models::payments::TimeRange, diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 9ca4dea4a1a..b26c030c367 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4828,6 +4828,14 @@ ], "nullable": true }, + "bank": { + "allOf": [ + { + "$ref": "#/components/schemas/MaskedBankDetails" + } + ], + "nullable": true + }, "requires_cvv": { "type": "boolean", "description": "Whether this payment method requires CVV to be collected", @@ -6434,6 +6442,17 @@ } ] }, + "MaskedBankDetails": { + "type": "object", + "required": [ + "mask" + ], + "properties": { + "mask": { + "type": "string" + } + } + }, "MbWayRedirection": { "type": "object", "required": [
2023-10-14T12:17:42Z
## 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 includes changes for tokenising the fetched bank details and return masked bank details while fetching the customer payment methods ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> List customer payment method - ![image](https://github.com/juspay/hyperswitch/assets/70657455/a9bc01d8-aeef-4ee2-b1cb-7fd0e99df685) Redis Entry - ![image](https://github.com/juspay/hyperswitch/assets/70657455/5aa3deab-3489-47aa-bb71-315c07e436e2) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
037e310aab5fac90ba33cdff2acda2f031261a6c
juspay/hyperswitch
juspay__hyperswitch-2833
Bug: [FEATURE] Add support for profile-specific default routing fallback ### Feature Description Currently every merchant has a default fallback which is a list of all of their configured connectors. We now want to make this profile-specific, i.e. each profile will have an associated default fallback that is a list of all the connectors associated with that profile. This issue also entails development of Read/Write APIs for profile specific default fallbacks, and integration with the payments core. Further on , we can also later on add the `mca_id` as many connectors with the same name can be there under a single `profile_id` ### Possible Implementation In interest of backwards compatibility, create two separate default fallback APIs for profiles (Read & Write). Additionally, implement profile-specific fallback usage in payments core routing with a feature flag. ### 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? No, but I'm happy to collaborate on a PR with someone else
diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs index 5eca01acc6f..a09735bc572 100644 --- a/crates/api_models/src/events/routing.rs +++ b/crates/api_models/src/events/routing.rs @@ -1,8 +1,9 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::routing::{ - LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, RoutingAlgorithmId, - RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind, + LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig, + RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind, + RoutingPayloadWrapper, }; #[cfg(feature = "business_profile_routing")] use crate::routing::{RoutingRetrieveLinkQuery, RoutingRetrieveQuery}; @@ -37,6 +38,17 @@ impl ApiEventMetric for LinkedRoutingConfigRetrieveResponse { } } +impl ApiEventMetric for RoutingPayloadWrapper { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} +impl ApiEventMetric for ProfileDefaultRoutingConfig { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} + #[cfg(feature = "business_profile_routing")] impl ApiEventMetric for RoutingRetrieveQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 425ca364191..363df5389a7 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -40,6 +40,12 @@ pub struct RoutingConfigRequest { pub profile_id: Option<String>, } +#[derive(Debug, serde::Serialize)] +pub struct ProfileDefaultRoutingConfig { + pub profile_id: String, + pub connectors: Vec<RoutableConnectorChoice>, +} + #[cfg(feature = "business_profile_routing")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveQuery { @@ -389,6 +395,13 @@ pub enum RoutingAlgorithmKind { Advanced, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] + +pub struct RoutingPayloadWrapper { + pub updated_config: Vec<RoutableConnectorChoice>, + pub profile_id: String, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde( tag = "type", diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index d765a5b5c5e..8f6906e0685 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -9,13 +9,13 @@ readme = "README.md" license.workspace = true [features] -default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts"] +default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "profile_specific_fallback_routing"] s3 = ["dep:aws-sdk-s3", "dep:aws-config"] kms = ["external_services/kms", "dep:aws-config"] email = ["external_services/email", "dep:aws-config"] basilisk = ["kms"] stripe = ["dep:serde_qs"] -release = ["kms", "stripe", "basilisk", "s3", "email", "business_profile_routing", "accounts_cache", "kv_store", "olap"] +release = ["kms", "stripe", "basilisk", "s3", "email", "business_profile_routing", "accounts_cache", "kv_store", "profile_specific_fallback_routing"] olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap"] oltp = ["data_models/oltp", "storage_impl/oltp"] kv_store = ["scheduler/kv_store"] @@ -24,6 +24,7 @@ openapi = ["olap", "oltp", "payouts"] vergen = ["router_env/vergen"] backwards_compatibility = ["api_models/backwards_compatibility", "euclid/backwards_compatibility", "kgraph_utils/backwards_compatibility"] business_profile_routing=["api_models/business_profile_routing"] +profile_specific_fallback_routing = [] dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector", "kgraph_utils/dummy_connector"] connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connector_choice_mca_id", "kgraph_utils/connector_choice_mca_id"] external_access_dc = ["dummy_connector"] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index e1e5ea744e2..5ccd9e96486 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -916,13 +916,16 @@ pub async fn create_payment_connector( let mut default_routing_config = routing_helpers::get_merchant_default_config(&*state.store, merchant_id).await?; + let mut default_routing_config_for_profile = + routing_helpers::get_merchant_default_config(&*state.clone().store, &profile_id).await?; + let mca = state .store .insert_merchant_connector_account(merchant_connector_account, &key_store) .await .to_duplicate_response( errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { - profile_id, + profile_id: profile_id.clone(), connector_name: req.connector_name.to_string(), }, )?; @@ -939,7 +942,7 @@ pub async fn create_payment_connector( }; if !default_routing_config.contains(&choice) { - default_routing_config.push(choice); + default_routing_config.push(choice.clone()); routing_helpers::update_merchant_default_config( &*state.store, merchant_id, @@ -947,6 +950,15 @@ pub async fn create_payment_connector( ) .await?; } + if !default_routing_config_for_profile.contains(&choice.clone()) { + default_routing_config_for_profile.push(choice); + routing_helpers::update_merchant_default_config( + &*state.store, + &profile_id.clone(), + default_routing_config_for_profile, + ) + .await?; + } } metrics::MCA_CREATE.add( diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 4134ddf65ea..3b89d4e38e4 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -71,7 +71,10 @@ pub struct SessionRoutingPmTypeInput<'a> { routing_algorithm: &'a MerchantAccountRoutingAlgorithm, backend_input: dsl_inputs::BackendInput, allowed_connectors: FxHashMap<String, api::GetToken>, - #[cfg(feature = "business_profile_routing")] + #[cfg(any( + feature = "business_profile_routing", + feature = "profile_specific_fallback_routing" + ))] profile_id: Option<String>, } static ROUTING_CACHE: StaticCache<CachedAlgorithm> = StaticCache::new(); @@ -207,10 +210,22 @@ pub async fn perform_static_routing_v1<F: Clone>( let algorithm_id = if let Some(id) = algorithm_ref.algorithm_id { id } else { - let fallback_config = - routing_helpers::get_merchant_default_config(&*state.clone().store, merchant_id) - .await - .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; + let fallback_config = routing_helpers::get_merchant_default_config( + &*state.clone().store, + #[cfg(not(feature = "profile_specific_fallback_routing"))] + merchant_id, + #[cfg(feature = "profile_specific_fallback_routing")] + { + payment_data + .payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::RoutingError::ProfileIdMissing)? + }, + ) + .await + .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; return Ok(fallback_config); }; @@ -616,10 +631,22 @@ pub async fn perform_fallback_routing<F: Clone>( eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { - let fallback_config = - routing_helpers::get_merchant_default_config(&*state.store, &key_store.merchant_id) - .await - .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; + let fallback_config = routing_helpers::get_merchant_default_config( + &*state.store, + #[cfg(not(feature = "profile_specific_fallback_routing"))] + &key_store.merchant_id, + #[cfg(feature = "profile_specific_fallback_routing")] + { + payment_data + .payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::RoutingError::ProfileIdMissing)? + }, + ) + .await + .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; let backend_input = make_dsl_input(payment_data)?; perform_kgraph_filtering( @@ -819,8 +846,11 @@ pub async fn perform_session_flow_routing( routing_algorithm: &routing_algorithm, backend_input: backend_input.clone(), allowed_connectors, - #[cfg(feature = "business_profile_routing")] - profile_id: session_input.payment_intent.clone().profile_id, + #[cfg(any( + feature = "business_profile_routing", + feature = "profile_specific_fallback_routing" + ))] + profile_id: session_input.payment_intent.profile_id.clone(), }; let maybe_choice = perform_session_routing_for_pm_type(session_pm_input).await?; @@ -880,7 +910,16 @@ async fn perform_session_routing_for_pm_type( } else { routing_helpers::get_merchant_default_config( &*session_pm_input.state.clone().store, + #[cfg(not(feature = "profile_specific_fallback_routing"))] merchant_id, + #[cfg(feature = "profile_specific_fallback_routing")] + { + session_pm_input + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::RoutingError::ProfileIdMissing)? + }, ) .await .change_context(errors::RoutingError::FallbackConfigFetchFailed)? @@ -903,7 +942,16 @@ async fn perform_session_routing_for_pm_type( if final_selection.is_empty() { let fallback = routing_helpers::get_merchant_default_config( &*session_pm_input.state.clone().store, + #[cfg(not(feature = "profile_specific_fallback_routing"))] merchant_id, + #[cfg(feature = "profile_specific_fallback_routing")] + { + session_pm_input + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::RoutingError::ProfileIdMissing)? + }, ) .await .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 723611ed500..4171c338563 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -13,13 +13,14 @@ use diesel_models::routing_algorithm::RoutingAlgorithm; use error_stack::{IntoReport, ResultExt}; use rustc_hash::FxHashSet; -#[cfg(feature = "business_profile_routing")] -use crate::core::utils::validate_and_get_business_profile; #[cfg(feature = "business_profile_routing")] use crate::types::transformers::{ForeignInto, ForeignTryInto}; use crate::{ consts, - core::errors::{RouterResponse, StorageErrorExt}, + core::{ + errors::{RouterResponse, StorageErrorExt}, + utils as core_utils, + }, routes::AppState, types::domain, utils::{self, OptionExt, ValueExt}, @@ -111,8 +112,12 @@ pub async fn create_routing_config( }) .attach_printable("Profile_id not provided")?; - validate_and_get_business_profile(db, Some(&profile_id), &merchant_account.merchant_id) - .await?; + core_utils::validate_and_get_business_profile( + db, + Some(&profile_id), + &merchant_account.merchant_id, + ) + .await?; helpers::validate_connectors_in_routing_config( db, @@ -229,7 +234,7 @@ pub async fn link_routing_config( .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?; - let business_profile = validate_and_get_business_profile( + let business_profile = core_utils::validate_and_get_business_profile( db, Some(&routing_algorithm.profile_id), &merchant_account.merchant_id, @@ -332,7 +337,7 @@ pub async fn retrieve_routing_config( .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; - validate_and_get_business_profile( + core_utils::validate_and_get_business_profile( db, Some(&routing_algorithm.profile_id), &merchant_account.merchant_id, @@ -401,9 +406,12 @@ pub async fn unlink_routing_config( field_name: "profile_id", }) .attach_printable("Profile_id not provided")?; - let business_profile = - validate_and_get_business_profile(db, Some(&profile_id), &merchant_account.merchant_id) - .await?; + let business_profile = core_utils::validate_and_get_business_profile( + db, + Some(&profile_id), + &merchant_account.merchant_id, + ) + .await?; match business_profile { Some(business_profile) => { let routing_algo_ref: routing_types::RoutingAlgorithmRef = business_profile @@ -622,13 +630,15 @@ pub async fn retrieve_linked_routing_config( #[cfg(feature = "business_profile_routing")] { let business_profiles = if let Some(profile_id) = query_params.profile_id { - validate_and_get_business_profile(db, Some(&profile_id), &merchant_account.merchant_id) - .await? - .map(|profile| vec![profile]) - .get_required_value("BusinessProfile") - .change_context(errors::ApiErrorResponse::BusinessProfileNotFound { - id: profile_id, - })? + core_utils::validate_and_get_business_profile( + db, + Some(&profile_id), + &merchant_account.merchant_id, + ) + .await? + .map(|profile| vec![profile]) + .get_required_value("BusinessProfile") + .change_context(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id })? } else { db.list_business_profile_by_merchant_id(&merchant_account.merchant_id) .await @@ -711,3 +721,118 @@ pub async fn retrieve_linked_routing_config( Ok(service_api::ApplicationResponse::Json(response)) } } + +pub async fn retrieve_default_routing_config_for_profiles( + state: AppState, + merchant_account: domain::MerchantAccount, +) -> RouterResponse<Vec<routing_types::ProfileDefaultRoutingConfig>> { + let db = state.store.as_ref(); + + let all_profiles = db + .list_business_profile_by_merchant_id(&merchant_account.merchant_id) + .await + .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound) + .attach_printable("error retrieving all business profiles for merchant")?; + + let retrieve_config_futures = all_profiles + .iter() + .map(|prof| helpers::get_merchant_default_config(db, &prof.profile_id)) + .collect::<Vec<_>>(); + + let configs = futures::future::join_all(retrieve_config_futures) + .await + .into_iter() + .collect::<Result<Vec<_>, _>>()?; + + let default_configs = configs + .into_iter() + .zip(all_profiles.iter().map(|prof| prof.profile_id.clone())) + .map( + |(config, profile_id)| routing_types::ProfileDefaultRoutingConfig { + profile_id, + connectors: config, + }, + ) + .collect::<Vec<_>>(); + + Ok(service_api::ApplicationResponse::Json(default_configs)) +} + +pub async fn update_default_routing_config_for_profile( + state: AppState, + merchant_account: domain::MerchantAccount, + updated_config: Vec<routing_types::RoutableConnectorChoice>, + profile_id: String, +) -> RouterResponse<routing_types::ProfileDefaultRoutingConfig> { + let db = state.store.as_ref(); + + let business_profile = core_utils::validate_and_get_business_profile( + db, + Some(&profile_id), + &merchant_account.merchant_id, + ) + .await? + .get_required_value("BusinessProfile") + .change_context(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id })?; + let default_config = + helpers::get_merchant_default_config(db, &business_profile.profile_id).await?; + + utils::when(default_config.len() != updated_config.len(), || { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "current config and updated config have different lengths".to_string(), + }) + .into_report() + })?; + + let existing_set = FxHashSet::from_iter(default_config.iter().map(|c| { + ( + c.connector.to_string(), + #[cfg(feature = "connector_choice_mca_id")] + c.merchant_connector_id.as_ref(), + #[cfg(not(feature = "connector_choice_mca_id"))] + c.sub_label.as_ref(), + ) + })); + + let updated_set = FxHashSet::from_iter(updated_config.iter().map(|c| { + ( + c.connector.to_string(), + #[cfg(feature = "connector_choice_mca_id")] + c.merchant_connector_id.as_ref(), + #[cfg(not(feature = "connector_choice_mca_id"))] + c.sub_label.as_ref(), + ) + })); + + let symmetric_diff = existing_set + .symmetric_difference(&updated_set) + .cloned() + .collect::<Vec<_>>(); + + utils::when(!symmetric_diff.is_empty(), || { + let error_str = symmetric_diff + .into_iter() + .map(|(connector, ident)| format!("'{connector}:{ident:?}'")) + .collect::<Vec<_>>() + .join(", "); + + Err(errors::ApiErrorResponse::InvalidRequestData { + message: format!("connector mismatch between old and new configs ({error_str})"), + }) + .into_report() + })?; + + helpers::update_merchant_default_config( + db, + &business_profile.profile_id, + updated_config.clone(), + ) + .await?; + + Ok(service_api::ApplicationResponse::Json( + routing_types::ProfileDefaultRoutingConfig { + profile_id: business_profile.profile_id, + connectors: updated_config, + }, + )) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index c34c542d1b6..7f5c720be60 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -324,6 +324,16 @@ impl Routing { web::resource("/{algorithm_id}/activate") .route(web::post().to(cloud_routing::routing_link_config)), ) + .service( + web::resource("/default/profile/{profile_id}").route( + web::post().to(cloud_routing::routing_update_default_config_for_profile), + ), + ) + .service( + web::resource("/default/profile").route( + web::get().to(cloud_routing::routing_retrieve_default_config_for_profiles), + ), + ) } } diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index b87116f47fc..606111a8881 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -296,3 +296,60 @@ pub async fn routing_retrieve_linked_config( .await } } + +#[cfg(feature = "olap")] +#[instrument(skip_all)] +pub async fn routing_retrieve_default_config_for_profiles( + state: web::Data<AppState>, + req: HttpRequest, +) -> impl Responder { + oss_api::server_wrap( + Flow::RoutingRetrieveDefaultConfig, + state, + &req, + (), + |state, auth: auth::AuthenticationData, _| { + routing::retrieve_default_routing_config_for_profiles(state, auth.merchant_account) + }, + #[cfg(not(feature = "release"))] + auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()), + #[cfg(feature = "release")] + &auth::JWTAuth, + api_locking::LockAction::NotApplicable, + ) + .await +} + +#[cfg(feature = "olap")] +#[instrument(skip_all)] +pub async fn routing_update_default_config_for_profile( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, + json_payload: web::Json<Vec<routing_types::RoutableConnectorChoice>>, +) -> impl Responder { + let routing_payload_wrapper = routing_types::RoutingPayloadWrapper { + updated_config: json_payload.into_inner(), + profile_id: path.into_inner(), + }; + oss_api::server_wrap( + Flow::RoutingUpdateDefaultConfig, + state, + &req, + routing_payload_wrapper, + |state, auth: auth::AuthenticationData, wrapper| { + routing::update_default_routing_config_for_profile( + state, + auth.merchant_account, + wrapper.updated_config, + wrapper.profile_id, + ) + }, + #[cfg(not(feature = "release"))] + auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()), + #[cfg(feature = "release")] + &auth::JWTAuth, + api_locking::LockAction::NotApplicable, + ) + .await +}
2023-11-08T07:55:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description `default-fallbacks` are defined specific to profile i.e every profile will correspond to different fallbacks and while deriving the fallbacks we are doing that based on profile. ### 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 tests will be same as this PR: https://github.com/juspay/hyperswitch-cloud/pull/2949 ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
f88eee7362be2cc3e8e8dc2bb7bfd263892ff01e
juspay/hyperswitch
juspay__hyperswitch-2526
Bug: [REFACTOR] delete requires cvv config when merchant account is deleted ### Feature Description Add support for removing the requires cvv config from configs table when merchant account is deleted. ### Possible Implementation When merchant account delete request is sent, delete an entry in configs with key = '{merchant_id}_requires_cvv' ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index ec229bd8a56..226d77d598e 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -491,6 +491,25 @@ pub async fn merchant_account_delete( .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; is_deleted = is_merchant_account_deleted && is_merchant_key_store_deleted; } + + match db + .delete_config_by_key(format!("{}_requires_cvv", merchant_id).as_str()) + .await + { + Ok(_) => Ok::<_, errors::ApiErrorResponse>(()), + Err(err) => { + if err.current_context().is_db_not_found() { + crate::logger::error!("requires_cvv config not found in db: {err:?}"); + Ok(()) + } else { + Err(err + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while deleting requires_cvv config"))? + } + } + } + .ok(); + let response = api::MerchantAccountDeleteResponse { merchant_id, deleted: is_deleted,
2023-10-10T08:03:09Z
## 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 includes changes for removing the requires cvv config from configs table when merchant account is deleted. ### 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)? --> ![image](https://github.com/juspay/hyperswitch/assets/70657455/d9b02042-104f-4b09-a5be-f4b49591dfd9) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cf0db35923d39caca9bf267b7d87a3f215884b66
juspay/hyperswitch
juspay__hyperswitch-2598
Bug: [CI] Add ci workflow for validating hotfix pr ### Feature Description Add support for creating a new workflow for validating the hotfix pr. Workflow should be triggered when baseRef is prefixed with hotfix- ### Possible Implementation Assumption - Hotfix PR description contains one or more original PR's link If description contains any issues link, it would be ignored Validations include - Among all the Original PR links added in Hotfix PR description, at least one has to satisfy the below conditions Original PR author should be same as Hotfix PR author Original PR title should be same as Hotfix PR title Original PR's baseRef has to be main Original PR should be merged to main If no Original PR has been found in description or if above condition doesn't satisfy for even one original PR's, CI check will fail ### 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!
2023-10-16T07:23:49Z
## 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 adds a new workflow for validating the hotfix PR. Workflow is triggered when baseRef of hotfix PR is prefixed with `hotfix-` **Assumption** - * Hotfix PR description contains one or more original PR's link * If description contains any issues link, it would be ignored **Validations include** - Among all the Original PR links added in Hotfix PR description, at least one has to satisfy the below conditions * Original PR author should be same as Hotfix PR author * Original PR title should be same as Hotfix PR title * Original PR's baseRef has to be main * Original PR should be merged to main If no Original PR has been found in description or if above condition doesn't satisfy for even one original PR's, CI check will 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). --> ## 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 passing ![image](https://github.com/juspay/hyperswitch/assets/70657455/431347b5-99d6-4d77-af6c-36d9028cca34) CI failing because Original PR is not merged ![image](https://github.com/juspay/hyperswitch/assets/70657455/1f6e1416-dfd2-4f7e-8bf9-a72468d8d8cb) CI failing because Original PR title does not match with hotfix PR title ![image](https://github.com/juspay/hyperswitch/assets/70657455/dab1e61d-c6c4-4cf7-b90f-b0333ed48aa1) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cecea8718a48b4e896b2bafce0f909ef8d9a6e8a
juspay/hyperswitch
juspay__hyperswitch-2510
Bug: [REFACTOR] remove ansi escape characters from logs when format is set to json ### Feature Description Fix log formatting by removing the ansi escape characters from logs when the log format is set to json ### Possible Implementation This will help in making the logs much cleaner as opposed to having ansi escape characters in json format. Set color mode of Report to None ### 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/Cargo.lock b/Cargo.lock index 9e026101d1a..abecaf6ae24 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4179,6 +4179,7 @@ version = "0.1.0" dependencies = [ "cargo_metadata 0.15.4", "config", + "error-stack", "gethostname", "once_cell", "opentelemetry", diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml index c72220f52d2..1181685d723 100644 --- a/crates/router_env/Cargo.toml +++ b/crates/router_env/Cargo.toml @@ -10,6 +10,7 @@ license.workspace = true [dependencies] cargo_metadata = "0.15.4" config = { version = "0.13.3", features = ["toml"] } +error-stack = "0.3.1" gethostname = "0.4.3" once_cell = "1.18.0" opentelemetry = { version = "0.19.0", features = ["rt-tokio-current-thread", "metrics"] } diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs index 313e64d0e9c..78cbe9f342f 100644 --- a/crates/router_env/src/logger/setup.rs +++ b/crates/router_env/src/logger/setup.rs @@ -101,6 +101,7 @@ pub fn setup( subscriber.with(logging_layer).init(); } config::LogFormat::Json => { + error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None); let logging_layer = FormattingLayer::new(service_name, console_writer).with_filter(console_filter); subscriber.with(logging_layer).init();
2023-10-09T11:46:27Z
## 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 includes changes for removing the ansi escape characters from logs when the logs format is set to json ### 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 will help in making the logs much cleaner as opposed to having ansi escape characters in json format ## 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)? --> Current log - ![image](https://github.com/juspay/hyperswitch/assets/70657455/e6658b04-23d4-41fd-af15-e8aba7b83c81) Log due to current PR changes - ![image](https://github.com/juspay/hyperswitch/assets/70657455/92e49a22-e1c7-449b-9519-286f0b1a2dbb) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
e02838eb5d3da97ef573926ded4a318ed24b6f1c
juspay/hyperswitch
juspay__hyperswitch-2504
Bug: [REFACTOR] Limiting `Tracing` to only Payments API ## Description We are tracing all the APIs, which isn't effective due to the variance of the traffic. This change will include the tracing layer to a specific scope instead of the entire application
diff --git a/config/config.example.toml b/config/config.example.toml index e980ea4fffd..b69519b6ac4 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -28,6 +28,7 @@ port = 5432 # DB Port dbname = "hyperswitch_db" # Name of Database pool_size = 5 # Number of connections to keep open connection_timeout = 10 # Timeout for database connection in seconds +queue_strategy = "Fifo" # Add the queue strategy used by the database bb8 client # Replica SQL data store credentials [replica_database] @@ -38,6 +39,7 @@ port = 5432 # DB Port dbname = "hyperswitch_db" # Name of Database pool_size = 5 # Number of connections to keep open connection_timeout = 10 # Timeout for database connection in seconds +queue_strategy = "Fifo" # Add the queue strategy used by the database bb8 client # Redis credentials [redis] @@ -93,6 +95,7 @@ sampling_rate = 0.1 # decimal rate between 0.0 otel_exporter_otlp_endpoint = "http://localhost:4317" # endpoint to send metrics and traces to, can include port number otel_exporter_otlp_timeout = 5000 # timeout (in milliseconds) for sending metrics and traces use_xray_generator = false # Set this to true for AWS X-ray compatible traces +route_to_trace = [ "*/confirm" ] # This section provides some secret values. [secrets] @@ -422,4 +425,4 @@ supported_connectors = "braintree" apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE" #Payment Processing Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Payment Processing Certificate apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" #Private key generate by Elliptic-curve prime256v1 curve apple_pay_merchant_cert = "APPLE_PAY_MERCHNAT_CERTIFICATE" #Merchant Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Merchant Identity Certificate -apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" #Private key generate by RSA:2048 algorithm \ No newline at end of file +apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" #Private key generate by RSA:2048 algorithm diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index ec06a6d7078..3bb1c31d180 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -29,6 +29,7 @@ impl Default for super::settings::Database { dbname: String::new(), pool_size: 5, connection_timeout: 10, + queue_strategy: Default::default(), } } } diff --git a/crates/router/src/configs/kms.rs b/crates/router/src/configs/kms.rs index 0491fb61fc6..317ad0608b4 100644 --- a/crates/router/src/configs/kms.rs +++ b/crates/router/src/configs/kms.rs @@ -61,6 +61,7 @@ impl KmsDecrypt for settings::Database { password: self.password.decrypt_inner(kms_client).await?.into(), pool_size: self.pool_size, connection_timeout: self.connection_timeout, + queue_strategy: self.queue_strategy.into(), }) } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index fd4a398fd56..70d05b79f96 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -464,6 +464,24 @@ pub struct Database { pub dbname: String, pub pool_size: u32, pub connection_timeout: u64, + pub queue_strategy: QueueStrategy, +} + +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(rename_all = "PascalCase")] +pub enum QueueStrategy { + #[default] + Fifo, + Lifo, +} + +impl From<QueueStrategy> for bb8::QueueStrategy { + fn from(value: QueueStrategy) -> Self { + match value { + QueueStrategy::Fifo => Self::Fifo, + QueueStrategy::Lifo => Self::Lifo, + } + } } #[cfg(not(feature = "kms"))] @@ -477,6 +495,7 @@ impl Into<storage_impl::config::Database> for Database { dbname: self.dbname, pool_size: self.pool_size, connection_timeout: self.connection_timeout, + queue_strategy: self.queue_strategy.into(), } } } @@ -704,9 +723,11 @@ impl Settings { .try_parsing(true) .separator("__") .list_separator(",") + .with_list_parse_key("log.telemetry.route_to_trace") .with_list_parse_key("redis.cluster_urls") .with_list_parse_key("connectors.supported.wallets") .with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id"), + ) .build()?; diff --git a/crates/router_env/src/logger/config.rs b/crates/router_env/src/logger/config.rs index 269759ed44f..664c0d508f5 100644 --- a/crates/router_env/src/logger/config.rs +++ b/crates/router_env/src/logger/config.rs @@ -101,6 +101,8 @@ pub struct LogTelemetry { pub otel_exporter_otlp_timeout: Option<u64>, /// Whether to use xray ID generator, (enable this if you plan to use AWS-XRAY) pub use_xray_generator: bool, + /// Route Based Tracing + pub route_to_trace: Option<Vec<String>>, } /// Telemetry / tracing. diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs index 78cbe9f342f..992de3e747e 100644 --- a/crates/router_env/src/logger/setup.rs +++ b/crates/router_env/src/logger/setup.rs @@ -12,6 +12,7 @@ use opentelemetry::{ trace::BatchConfig, Resource, }, + trace::{TraceContextExt, TraceState}, KeyValue, }; use opentelemetry_otlp::{TonicExporterBuilder, WithExportConfig}; @@ -132,6 +133,92 @@ fn get_opentelemetry_exporter(config: &config::LogTelemetry) -> TonicExporterBui exporter_builder } +#[derive(Debug, Clone)] +enum TraceUrlAssert { + Match(String), + EndsWith(String), +} + +impl TraceUrlAssert { + fn compare_url(&self, url: &str) -> bool { + match self { + Self::Match(value) => url == value, + Self::EndsWith(end) => url.ends_with(end), + } + } +} + +impl From<String> for TraceUrlAssert { + fn from(value: String) -> Self { + match value { + url if url.starts_with('*') => Self::EndsWith(url.trim_start_matches('*').to_string()), + url => Self::Match(url), + } + } +} + +#[derive(Debug, Clone)] +struct TraceAssertion { + clauses: Option<Vec<TraceUrlAssert>>, + /// default behaviour for tracing if no condition is provided + default: bool, +} + +impl TraceAssertion { + /// + /// Should the provided url be traced + /// + fn should_trace_url(&self, url: &str) -> bool { + match &self.clauses { + Some(clauses) => clauses.iter().all(|cur| cur.compare_url(url)), + None => self.default, + } + } +} + +/// +/// Conditional Sampler for providing control on url based tracing +/// +#[derive(Clone, Debug)] +struct ConditionalSampler<T: trace::ShouldSample + Clone + 'static>(TraceAssertion, T); + +impl<T: trace::ShouldSample + Clone + 'static> trace::ShouldSample for ConditionalSampler<T> { + fn should_sample( + &self, + parent_context: Option<&opentelemetry::Context>, + trace_id: opentelemetry::trace::TraceId, + name: &str, + span_kind: &opentelemetry::trace::SpanKind, + attributes: &opentelemetry::trace::OrderMap<opentelemetry::Key, opentelemetry::Value>, + links: &[opentelemetry::trace::Link], + instrumentation_library: &opentelemetry::InstrumentationLibrary, + ) -> opentelemetry::trace::SamplingResult { + match attributes + .get(&opentelemetry::Key::new("http.route")) + .map_or(self.0.default, |inner| { + self.0.should_trace_url(&inner.as_str()) + }) { + true => self.1.should_sample( + parent_context, + trace_id, + name, + span_kind, + attributes, + links, + instrumentation_library, + ), + false => opentelemetry::trace::SamplingResult { + decision: opentelemetry::trace::SamplingDecision::Drop, + attributes: Vec::new(), + trace_state: match parent_context { + Some(ctx) => ctx.span().span_context().trace_state().clone(), + None => TraceState::default(), + }, + }, + } + } +} + fn setup_tracing_pipeline( config: &config::LogTelemetry, service_name: &str, @@ -140,9 +227,16 @@ fn setup_tracing_pipeline( global::set_text_map_propagator(TraceContextPropagator::new()); let mut trace_config = trace::config() - .with_sampler(trace::Sampler::TraceIdRatioBased( - config.sampling_rate.unwrap_or(1.0), - )) + .with_sampler(trace::Sampler::ParentBased(Box::new(ConditionalSampler( + TraceAssertion { + clauses: config + .route_to_trace + .clone() + .map(|inner| inner.into_iter().map(Into::into).collect()), + default: false, + }, + trace::Sampler::TraceIdRatioBased(config.sampling_rate.unwrap_or(1.0)), + )))) .with_resource(Resource::new(vec![KeyValue::new( "service.name", service_name.to_owned(), diff --git a/crates/storage_impl/src/config.rs b/crates/storage_impl/src/config.rs index ad543b1942a..ceed3da81b3 100644 --- a/crates/storage_impl/src/config.rs +++ b/crates/storage_impl/src/config.rs @@ -9,4 +9,5 @@ pub struct Database { pub dbname: String, pub pool_size: u32, pub connection_timeout: u64, + pub queue_strategy: bb8::QueueStrategy, } diff --git a/crates/storage_impl/src/database/store.rs b/crates/storage_impl/src/database/store.rs index f9a7450b1cd..a09f1b75256 100644 --- a/crates/storage_impl/src/database/store.rs +++ b/crates/storage_impl/src/database/store.rs @@ -88,6 +88,7 @@ pub async fn diesel_make_pg_pool( let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url); let mut pool = bb8::Pool::builder() .max_size(database.pool_size) + .queue_strategy(database.queue_strategy) .connection_timeout(std::time::Duration::from_secs(database.connection_timeout)); if test_transaction {
2023-10-09T12:09:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This change introduces a new middleware for tracing requests with the specified url. Providing a filtration mechanism. This change also includes changing the bb8 queue strategy from FIFO to LIFO. ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
14cf0e735a31a823a1909a2886a3fedb4a9ea3e1
juspay/hyperswitch
juspay__hyperswitch-2432
Bug: [REFACTOR] add `requires_cvv` config while creating merchant account ### Feature Description Insert requires_cvv config during merchant account creation itself. while getting that config during list_customer_payment_method, if not found in db, we insert it into db. ### Possible Implementation in order to reduce db call in during listing payment methods, we insert config for requires_cvv during merchant creation itself ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index dabe22da626..c7009bf4cc9 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -219,6 +219,17 @@ pub async fn create_merchant_account( .insert_merchant(merchant_account, &key_store) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; + + db.insert_config(diesel_models::configs::ConfigNew { + key: format!("{}_requires_cvv", merchant_account.merchant_id), + config: "true".to_string(), + }) + .await + .map_err(|err| { + crate::logger::error!("Error while setting requires_cvv config: {err:?}"); + }) + .ok(); + Ok(service_api::ApplicationResponse::Json( merchant_account .try_into() diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index c22b7323095..20a3e130eb2 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1831,7 +1831,7 @@ pub async fn list_customer_payment_method( ) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to fetch merchant_id config for requires_cvv")?; + .attach_printable("Failed to fetch requires_cvv config")?; let requires_cvv = is_requires_cvv.config != "false";
2023-10-03T13:39:33Z
## 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 includes changes for inserting requires_cvv config during merchant account creation itself. while getting that config during `list_customer_payment_method`, if not found in db, we insert it into db. ### 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)? --> ![image](https://github.com/juspay/hyperswitch/assets/70657455/5daec1a0-4a85-4896-b183-86fb585e0a0d) ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d177b4d94f08fb8ef44b5c07ec1bdc771baa016d
juspay/hyperswitch
juspay__hyperswitch-2438
Bug: [FEATURE] Implement `MerchantAccountInterface` for `MockDb` Spin off from #172. Refer to the parent issue for more information
diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs index b1dcc1d3476..12d51311e87 100644 --- a/crates/diesel_models/src/merchant_account.rs +++ b/crates/diesel_models/src/merchant_account.rs @@ -260,6 +260,36 @@ pub struct MerchantAccountUpdateInternal { pub recon_status: Option<storage_enums::ReconStatus>, } +#[cfg(feature = "v2")] +impl MerchantAccountUpdateInternal { + pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount { + let Self { + merchant_name, + merchant_details, + publishable_key, + storage_scheme, + metadata, + modified_at, + organization_id, + recon_status, + } = self; + + MerchantAccount { + merchant_name: merchant_name.or(source.merchant_name), + merchant_details: merchant_details.or(source.merchant_details), + publishable_key: publishable_key.or(source.publishable_key), + storage_scheme: storage_scheme.unwrap_or(source.storage_scheme), + metadata: metadata.or(source.metadata), + created_at: source.created_at, + modified_at, + organization_id: organization_id.unwrap_or(source.organization_id), + recon_status: recon_status.unwrap_or(source.recon_status), + version: source.version, + id: source.id, + } + } +} + #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] @@ -290,3 +320,71 @@ pub struct MerchantAccountUpdateInternal { pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, } + +#[cfg(feature = "v1")] +impl MerchantAccountUpdateInternal { + pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount { + let Self { + merchant_name, + merchant_details, + return_url, + webhook_details, + sub_merchants_enabled, + parent_merchant_id, + enable_payment_response_hash, + payment_response_hash_key, + redirect_to_merchant_with_http_post, + publishable_key, + storage_scheme, + locker_id, + metadata, + routing_algorithm, + primary_business_details, + modified_at, + intent_fulfillment_time, + frm_routing_algorithm, + payout_routing_algorithm, + organization_id, + is_recon_enabled, + default_profile, + recon_status, + payment_link_config, + pm_collect_link_config, + } = self; + + MerchantAccount { + merchant_id: source.merchant_id, + return_url: return_url.or(source.return_url), + enable_payment_response_hash: enable_payment_response_hash + .unwrap_or(source.enable_payment_response_hash), + payment_response_hash_key: payment_response_hash_key + .or(source.payment_response_hash_key), + redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post + .unwrap_or(source.redirect_to_merchant_with_http_post), + merchant_name: merchant_name.or(source.merchant_name), + merchant_details: merchant_details.or(source.merchant_details), + webhook_details: webhook_details.or(source.webhook_details), + sub_merchants_enabled: sub_merchants_enabled.or(source.sub_merchants_enabled), + parent_merchant_id: parent_merchant_id.or(source.parent_merchant_id), + publishable_key: publishable_key.or(source.publishable_key), + storage_scheme: storage_scheme.unwrap_or(source.storage_scheme), + locker_id: locker_id.or(source.locker_id), + metadata: metadata.or(source.metadata), + routing_algorithm: routing_algorithm.or(source.routing_algorithm), + primary_business_details: primary_business_details + .unwrap_or(source.primary_business_details), + intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time), + created_at: source.created_at, + modified_at, + frm_routing_algorithm: frm_routing_algorithm.or(source.frm_routing_algorithm), + payout_routing_algorithm: payout_routing_algorithm.or(source.payout_routing_algorithm), + organization_id: organization_id.unwrap_or(source.organization_id), + is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled), + default_profile: default_profile.unwrap_or(source.default_profile), + recon_status: recon_status.unwrap_or(source.recon_status), + payment_link_config: payment_link_config.or(source.payment_link_config), + pm_collect_link_config: pm_collect_link_config.or(source.pm_collect_link_config), + version: source.version, + } + } +} diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index 3e860d36284..1e3302dab4a 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -201,7 +201,7 @@ impl MerchantAccount { #[cfg(feature = "v1")] #[allow(clippy::large_enum_variant)] -#[derive(Debug)] +#[derive(Debug, Clone)] pub enum MerchantAccountUpdate { Update { merchant_name: OptionalEncryptableName, @@ -237,7 +237,7 @@ pub enum MerchantAccountUpdate { #[cfg(feature = "v2")] #[allow(clippy::large_enum_variant)] -#[derive(Debug)] +#[derive(Debug, Clone)] pub enum MerchantAccountUpdate { Update { merchant_name: OptionalEncryptableName, diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index 13a778001ae..39844503892 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -482,91 +482,225 @@ impl MerchantAccountInterface for MockDb { merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let accounts = self.merchant_accounts.lock().await; - let account: Option<domain::MerchantAccount> = accounts + accounts .iter() .find(|account| account.get_id() == merchant_id) .cloned() - .async_map(|a| async { - a.convert( - state, - merchant_key_store.key.get_inner(), - merchant_key_store.merchant_id.clone().into(), - ) - .await - .change_context(errors::StorageError::DecryptionError) - }) + .ok_or(errors::StorageError::ValueNotFound(format!( + "Merchant ID: {:?} not found", + merchant_id + )))? + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) .await - .transpose()?; - - match account { - Some(account) => Ok(account), - // [#172]: Implement function for `MockDb` - None => Err(errors::StorageError::MockDbError)?, - } + .change_context(errors::StorageError::DecryptionError) } async fn update_merchant( &self, - _state: &KeyManagerState, - _this: domain::MerchantAccount, - _merchant_account: storage::MerchantAccountUpdate, - _merchant_key_store: &domain::MerchantKeyStore, + state: &KeyManagerState, + merchant_account: domain::MerchantAccount, + merchant_account_update: storage::MerchantAccountUpdate, + merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let merchant_id = merchant_account.get_id().to_owned(); + let mut accounts = self.merchant_accounts.lock().await; + accounts + .iter_mut() + .find(|account| account.get_id() == merchant_account.get_id()) + .async_map(|account| async { + let update = MerchantAccountUpdateInternal::from(merchant_account_update) + .apply_changeset( + Conversion::convert(merchant_account) + .await + .change_context(errors::StorageError::EncryptionError)?, + ); + *account = update.clone(); + update + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError) + }) + .await + .transpose()? + .ok_or( + errors::StorageError::ValueNotFound(format!( + "Merchant ID: {:?} not found", + merchant_id + )) + .into(), + ) } async fn update_specific_fields_in_merchant( &self, - _state: &KeyManagerState, - _merchant_id: &common_utils::id_type::MerchantId, - _merchant_account: storage::MerchantAccountUpdate, - _merchant_key_store: &domain::MerchantKeyStore, + state: &KeyManagerState, + merchant_id: &common_utils::id_type::MerchantId, + merchant_account_update: storage::MerchantAccountUpdate, + merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { - // [#TODO]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut accounts = self.merchant_accounts.lock().await; + accounts + .iter_mut() + .find(|account| account.get_id() == merchant_id) + .async_map(|account| async { + let update = MerchantAccountUpdateInternal::from(merchant_account_update) + .apply_changeset(account.clone()); + *account = update.clone(); + update + .convert( + state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError) + }) + .await + .transpose()? + .ok_or( + errors::StorageError::ValueNotFound(format!( + "Merchant ID: {:?} not found", + merchant_id + )) + .into(), + ) } async fn find_merchant_account_by_publishable_key( &self, - _state: &KeyManagerState, - _publishable_key: &str, + state: &KeyManagerState, + publishable_key: &str, ) -> CustomResult<authentication::AuthenticationData, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let accounts = self.merchant_accounts.lock().await; + let account = accounts + .iter() + .find(|account| { + account + .publishable_key + .as_ref() + .is_some_and(|key| key == publishable_key) + }) + .ok_or(errors::StorageError::ValueNotFound(format!( + "Publishable Key: {} not found", + publishable_key + )))?; + let key_store = self + .get_merchant_key_store_by_merchant_id( + state, + account.get_id(), + &self.get_master_key().to_vec().into(), + ) + .await?; + Ok(authentication::AuthenticationData { + merchant_account: account + .clone() + .convert( + state, + key_store.key.get_inner(), + key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError)?, + + key_store, + profile_id: None, + }) } async fn update_all_merchant_account( &self, - _merchant_account_update: storage::MerchantAccountUpdate, + merchant_account_update: storage::MerchantAccountUpdate, ) -> CustomResult<usize, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + let mut accounts = self.merchant_accounts.lock().await; + Ok(accounts.iter_mut().fold(0, |acc, account| { + let update = MerchantAccountUpdateInternal::from(merchant_account_update.clone()) + .apply_changeset(account.clone()); + *account = update; + acc + 1 + })) } async fn delete_merchant_account_by_merchant_id( &self, - _merchant_id: &common_utils::id_type::MerchantId, + merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut accounts = self.merchant_accounts.lock().await; + accounts.retain(|x| x.get_id() != merchant_id); + Ok(true) } #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, - _state: &KeyManagerState, - _organization_id: &common_utils::id_type::OrganizationId, + state: &KeyManagerState, + organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + let accounts = self.merchant_accounts.lock().await; + let futures = accounts + .iter() + .filter(|account| account.organization_id == *organization_id) + .map(|account| async { + let key_store = self + .get_merchant_key_store_by_merchant_id( + state, + account.get_id(), + &self.get_master_key().to_vec().into(), + ) + .await; + match key_store { + Ok(key) => account + .clone() + .convert(state, key.key.get_inner(), key.merchant_id.clone().into()) + .await + .change_context(errors::StorageError::DecryptionError), + Err(err) => Err(err), + } + }); + futures::future::join_all(futures) + .await + .into_iter() + .collect() } #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, - _state: &KeyManagerState, - _merchant_ids: Vec<common_utils::id_type::MerchantId>, + state: &KeyManagerState, + merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { - Err(errors::StorageError::MockDbError)? + let accounts = self.merchant_accounts.lock().await; + let futures = accounts + .iter() + .filter(|account| merchant_ids.contains(account.get_id())) + .map(|account| async { + let key_store = self + .get_merchant_key_store_by_merchant_id( + state, + account.get_id(), + &self.get_master_key().to_vec().into(), + ) + .await; + match key_store { + Ok(key) => account + .clone() + .convert(state, key.key.get_inner(), key.merchant_id.clone().into()) + .await + .change_context(errors::StorageError::DecryptionError), + Err(err) => Err(err), + } + }); + futures::future::join_all(futures) + .await + .into_iter() + .collect() } } diff --git a/docker-compose-development.yml b/docker-compose-development.yml index 3878f880b06..07a2131c6d4 100644 --- a/docker-compose-development.yml +++ b/docker-compose-development.yml @@ -64,6 +64,7 @@ services: FROM rust:latest RUN apt-get update && \ apt-get install -y protobuf-compiler + RUN rustup component add rustfmt clippy command: cargo run --bin router -- -f ./config/docker_compose.toml working_dir: /app ports:
2024-10-10T01:07:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Mockdb is a stub to avoid costly interactions with db during testing. This PR powers mockdb to have [MerchantAccountInterface](https://github.com/juspay/hyperswitch/blob/3d70b1a31703c5316183adaa9312a38e598fce01/crates/router/src/db/merchant_account.rs#L26) for adding, deleting, searching merchant accounts. ### 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). --> Fixes https://github.com/juspay/hyperswitch/issues/2438 ## 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] addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
33bc83fce47c579457f1b9be0a91bb4fa13585ff
juspay/hyperswitch
juspay__hyperswitch-2400
Bug: [Docs] : Some links not working ## Some index links are not working - Quick start guide - Fast integration for stripe users - Supported Features - Faq ### Video https://github.com/juspay/hyperswitch/assets/101205226/70f42b41-4c94-40fb-a538-85ef5ac4dd6c
diff --git a/README.md b/README.md index 3306de28704..cc19670a8fc 100644 --- a/README.md +++ b/README.md @@ -10,17 +10,17 @@ The single API to access payment ecosystems across 130+ countries</div> <p align="center"> - <a href="#quick-start-guide">Quick Start Guide</a> • - <a href="#fast-integration-for-stripe-users">Fast Integration for Stripe Users</a> • - <a href="#supported-features">Supported Features</a> • - <a href="#faqs">FAQs</a> + <a href="#%EF%B8%8F-quick-start-guide">Quick Start Guide</a> • + <a href="#-fast-integration-for-stripe-users">Fast Integration for Stripe Users</a> • + <a href="#-supported-features">Supported Features</a> • + <a href="#-FAQs">FAQs</a> <br> <a href="#whats-included">What's Included</a> • - <a href="#join-us-in-building-hyperswitch">Join us in building HyperSwitch</a> • - <a href="#community">Community</a> • - <a href="#bugs-and-feature-requests">Bugs and feature requests</a> • - <a href="#versioning">Versioning</a> • - <a href="#copyright-and-license">Copyright and License</a> + <a href="#-join-us-in-building-hyperswitch">Join us in building HyperSwitch</a> • + <a href="#-community">Community</a> • + <a href="#-bugs-and-feature-requests">Bugs and feature requests</a> • + <a href="#-versioning">Versioning</a> • + <a href="#%EF%B8%8F-copyright-and-license">Copyright and License</a> </p> <p align="center"> @@ -63,7 +63,9 @@ Using Hyperswitch, you can: <br> <img src="./docs/imgs/hyperswitch-product.png" alt="Hyperswitch-Product" width="50%"/> -## ⚡️ Quick Start Guide +<a href="#Quick Start Guide"> + <h2 id="Quick Start Guide">⚡️ Quick Start Guide</h2> +</a> <a href="https://app.hyperswitch.io/register"><img src="./docs/imgs/signup-to-hs.svg" height="35"></a> @@ -84,7 +86,9 @@ Ways to get started with Hyperswitch: setup required in your system. Suitable if you like to customise the core offering, [setup guide](/docs/try_local_system.md) -## 🔌 Fast Integration for Stripe Users +<a href="#Fast-Integration-for-Stripe-Users"> + <h2 id="Fast Integration for Stripe Users">🔌 Fast Integration for Stripe Users</h2> +</a> If you are already using Stripe, integrating with Hyperswitch is fun, fast & easy. @@ -97,7 +101,9 @@ Try the steps below to get a feel for how quick the setup is: [dashboard]: https://app.hyperswitch.io/register [migrate-from-stripe]: https://hyperswitch.io/docs/migrateFromStripe -## ✅ Supported Features +<a href="#Supported-Features"> + <h2 id="Supported Features">✅ Supported Features</h2> +</a> ### 🌟 Supported Payment Processors and Methods @@ -141,7 +147,9 @@ analytics, and operations end-to-end: You can [try the hosted version in our sandbox][dashboard]. -## 🤔 FAQs +<a href="#FAQs"> + <h2 id="FAQs">🤔 FAQs</h2> +</a> Got more questions? Please refer to our [FAQs page][faqs]. @@ -160,7 +168,9 @@ Please refer to the following documentation pages: - Router Architecture [Link] --> -## What's Included❓ +<a href="#what's-Included❓"> + <h2 id="what's-Included❓">What's Included❓</h2> +</a> Within the repositories, you'll find the following directories and files, logically grouping common assets and providing both compiled and minified @@ -208,7 +218,9 @@ should be introduced, checking it agrees with the actual structure --> └── scripts : automation, testing, and other utility scripts ``` -## 💪 Join us in building Hyperswitch +<a href="#Join-us-in-building-Hyperswitch"> + <h2 id="Join-us-in-building-Hyperswitch">💪 Join us in building Hyperswitch</h2> +</a> ### 🤝 Our Belief @@ -260,7 +272,9 @@ readability over purely idiomatic code. For example, some of the code in core functions (e.g., `payments_core`) is written to be more readable than pure-idiomatic. -## 👥 Community +<a href="#Community"> + <h2 id="Community">👥 Community</h2> +</a> Get updates on Hyperswitch development and chat with the community: @@ -292,7 +306,9 @@ Get updates on Hyperswitch development and chat with the community: </div> </div> -## 🐞 Bugs and feature requests +<a href="#Bugs and feature requests"> + <h2 id="Bugs and feature requests">🐞 Bugs and feature requests</h2> +</a> Please read the issue guidelines and search for [existing and closed issues]. If your problem or idea is not addressed yet, please [open a new issue]. @@ -300,16 +316,22 @@ If your problem or idea is not addressed yet, please [open a new issue]. [existing and closed issues]: https://github.com/juspay/hyperswitch/issues [open a new issue]: https://github.com/juspay/hyperswitch/issues/new/choose -## 🔖 Versioning +<a href="#Versioning"> + <h2 id="Versioning">🔖 Versioning</h2> +</a> Check the [CHANGELOG.md](./CHANGELOG.md) file for details. -## ©️ Copyright and License +<a href="#©Copyright and License"> + <h2 id="©Copyright and License">©️ Copyright and License</h2> +</a> This product is licensed under the [Apache 2.0 License](LICENSE). -## ✨ Thanks to all contributors +<a href="#Thanks to all contributors"> + <h2 id="Thanks to all contributors">✨ Thanks to all contributors</h2> +</a> Thank you for your support in hyperswitch's growth. Keep up the great work! 🥂
2023-10-01T07:16:56Z
## 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 --> ### 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 Readme hyperlinks not working ## How did you test it? in my forked repo ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d8a1bdd3ae0156e0b1da551b50814f7599d6e813
juspay/hyperswitch
juspay__hyperswitch-2351
Bug: [FEATURE]: [Worldline] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index f11c2398080..8d18723f9ed 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -565,12 +565,12 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, PaymentsResponseData item.response.capture_method, )), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.id), }), ..item.data }) @@ -616,12 +616,14 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, PaymentsResp item.response.payment.capture_method, )), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.payment.id), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.payment.id.clone(), + ), redirection_data, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.payment.id), }), ..item.data })
2023-10-29T15:30:07Z
## 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 --> https://github.com/juspay/hyperswitch/issues/2351 ### 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)? --> Make any Payment for connector Worldline and see that you are getting "reference_id" field in the payments response of hyperswitch. It should not be 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8125ea19912f6d6446412d13842e35545cc1a484
juspay/hyperswitch
juspay__hyperswitch-2350
Bug: [FEATURE]: [Tsys] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs index 5aa4574c91e..d8516c8293b 100644 --- a/crates/router/src/connector/tsys/transformers.rs +++ b/crates/router/src/connector/tsys/transformers.rs @@ -192,12 +192,14 @@ fn get_error_response( fn get_payments_response(connector_response: TsysResponse) -> types::PaymentsResponseData { types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(connector_response.transaction_id), + resource_id: types::ResponseId::ConnectorTransactionId( + connector_response.transaction_id.clone(), + ), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(connector_response.transaction_id), } } @@ -215,7 +217,12 @@ fn get_payments_sync_response( mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some( + connector_response + .transaction_details + .transaction_id + .clone(), + ), } }
2023-10-11T12:40:42Z
## Type of Change - [x] New feature ## Description The `connector_response_reference_id` parameter has been set for the Tsys Payment Solutions for uniform reference and transaction tracking. ### File Changes - [x] This PR modifies the Tsys Transformers file. **Location- router/src/connector/tsys/transformers.rs** ## Motivation and Context This PR was raised so that it Fixes #2350 ! ## How did you test it? - **I ran the following command, and all the errors were addressed properly, and the build was successful.** ```bash cargo clippy --all-features ``` ![build](https://github.com/juspay/hyperswitch/assets/47860497/39d95c9a-d14b-44c5-a402-9bd9cecf8b8e) - The code changes were formatted with the following command to fix styling issues. ```bash cargo +nightly fmt ``` ## 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
62638c4230bfd149c43c2805cbad0ce9be5386b3
juspay/hyperswitch
juspay__hyperswitch-2349
Bug: [FEATURE]: [Square] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index ff33914c4fd..01ed507bf34 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -327,6 +327,7 @@ pub struct SquarePaymentsResponseDetails { status: SquarePaymentStatus, id: String, amount_money: SquarePaymentsAmountData, + reference_id: Option<String>, } #[derive(Debug, Deserialize)] pub struct SquarePaymentsResponse { @@ -355,7 +356,7 @@ impl<F, T> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: item.response.payment.reference_id, }), amount_captured, ..item.data
2023-10-03T14:40:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Populated reference ID from the response ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as payment_id, attempt_id, and connector_transaction_id for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ## 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` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
0aa6b30d2c9056e9a21a88bdc064daa7e8659bd6
juspay/hyperswitch
juspay__hyperswitch-2348
Bug: [FEATURE]: [Stax] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 42c7c02a363..4ee28be1937 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -23,6 +23,7 @@ pub struct StaxPaymentsRequest { is_refundable: bool, pre_auth: bool, meta: StaxPaymentsRequestMetaData, + idempotency_id: Option<String>, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { @@ -51,6 +52,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { Err(errors::ConnectorError::InvalidWalletToken)? } }), + idempotency_id: Some(item.connector_request_reference_id.clone()), }) } api::PaymentMethodData::BankDebit( @@ -69,6 +71,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { Err(errors::ConnectorError::InvalidWalletToken)? } }), + idempotency_id: Some(item.connector_request_reference_id.clone()), }) } api::PaymentMethodData::BankDebit(_) @@ -282,6 +285,7 @@ pub struct StaxPaymentsResponse { child_captures: Vec<StaxChildCapture>, #[serde(rename = "type")] payment_response_type: StaxPaymentResponseTypes, + idempotency_id: Option<String>, } #[derive(Debug, Deserialize, Serialize)] @@ -323,12 +327,14 @@ impl<F, T> Ok(Self { status, response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some( + item.response.idempotency_id.unwrap_or(item.response.id), + ), }), ..item.data })
2023-10-02T10:52:24Z
## 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 fixes #2348 issue in STAX and uses connector_response_reference_id as reference to merchant. ### 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). --> Fixes #2348 and fixes #2317. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
36805411772da00719a716d05c650f10ca990d49
juspay/hyperswitch
juspay__hyperswitch-2346
Bug: [FEATURE]: [Rapyd] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - Please refer to the Rapyd API documentation [here](https://docs.rapyd.net/en/create-payment.html). In the payment response, there is a field called `merchant_reference_id` (an optional field). This `merchant_reference_id` needs to be mapped to the `connector_response_reference_id`. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 044a64b413c..6689c5b46f4 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -274,6 +274,7 @@ pub struct ResponseData { pub country_code: Option<String>, pub captured: Option<bool>, pub transaction_id: String, + pub merchant_reference_id: Option<String>, pub paid: Option<bool>, pub failure_code: Option<String>, pub failure_message: Option<String>, @@ -478,7 +479,9 @@ impl<F, T> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: data + .merchant_reference_id + .to_owned(), incremental_authorization_allowed: None, charge_id: None, }),
2024-10-14T06:50:16Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add connector_response_reference_id support for Rapyd - Used `merchant_reference_id` as the reference id, while implementing this! Resolves #2346 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9597215a66e38b0021bd804ffe4d9d040e30f8f9
juspay/hyperswitch
juspay__hyperswitch-2441
Bug: [REFACTOR] add support for passing context generic to api calls ### Feature Description Add support for including a new generic, context, which will be passed during api call (server_wrap) to call the related implementation depending on context ### Possible Implementation To have multiple implementation to a particular object and calling the respective implementation during runtime depending on the context passed ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index e44ce0a1fd3..1076dfe410f 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -6,7 +6,7 @@ use router_env::{instrument, tracing, Flow}; use crate::{ compatibility::{stripe::errors, wrap}, - core::{api_locking::GetLockingInput, payments}, + core::{api_locking::GetLockingInput, payment_methods::Oss, payments}, routes, services::{api, authentication as auth}, types::api::{self as api_types}, @@ -50,7 +50,7 @@ pub async fn payment_intents_create( &req, create_payment_req, |state, auth, req| { - payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, auth.key_store, @@ -109,7 +109,7 @@ pub async fn payment_intents_retrieve( &req, payload, |state, auth, payload| { - payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _, Oss>( state, auth.merchant_account, auth.key_store, @@ -172,7 +172,7 @@ pub async fn payment_intents_retrieve_with_gateway_creds( &req, payload, |state, auth, req| { - payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, auth.key_store, @@ -236,7 +236,7 @@ pub async fn payment_intents_update( &req, payload, |state, auth, req| { - payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, auth.key_store, @@ -302,7 +302,7 @@ pub async fn payment_intents_confirm( &req, payload, |state, auth, req| { - payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Authorize, api_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, auth.key_store, @@ -358,7 +358,7 @@ pub async fn payment_intents_capture( &req, payload, |state, auth, payload| { - payments::payments_core::<api_types::Capture, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Capture, api_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, auth.key_store, @@ -418,7 +418,7 @@ pub async fn payment_intents_cancel( &req, payload, |state, auth, req| { - payments::payments_core::<api_types::Void, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Void, api_types::PaymentsResponse, _, _, _, Oss>( state, auth.merchant_account, auth.key_store, diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index b9da2f8e3ee..311498e1af5 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -9,7 +9,7 @@ use crate::{ stripe::{errors, payment_intents::types as stripe_payment_types}, wrap, }, - core::{api_locking, payments}, + core::{api_locking, payment_methods::Oss, payments}, routes, services::{api, authentication as auth}, types::api as api_types, @@ -54,7 +54,14 @@ pub async fn setup_intents_create( &req, create_payment_req, |state, auth, req| { - payments::payments_core::<api_types::SetupMandate, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::< + api_types::SetupMandate, + api_types::PaymentsResponse, + _, + _, + _, + Oss, + >( state, auth.merchant_account, auth.key_store, @@ -113,7 +120,7 @@ pub async fn setup_intents_retrieve( &req, payload, |state, auth, payload| { - payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::PSync, api_types::PaymentsResponse, _, _, _, Oss>( state, auth.merchant_account, auth.key_store, @@ -178,7 +185,14 @@ pub async fn setup_intents_update( &req, payload, |state, auth, req| { - payments::payments_core::<api_types::SetupMandate, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::< + api_types::SetupMandate, + api_types::PaymentsResponse, + _, + _, + _, + Oss, + >( state, auth.merchant_account, auth.key_store, @@ -244,7 +258,14 @@ pub async fn setup_intents_confirm( &req, payload, |state, auth, req| { - payments::payments_core::<api_types::SetupMandate, api_types::PaymentsResponse, _, _, _>( + payments::payments_core::< + api_types::SetupMandate, + api_types::PaymentsResponse, + _, + _, + _, + Oss, + >( state, auth.merchant_account, auth.key_store, diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index f1d641adbe5..850daeba75f 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -1,3 +1,99 @@ pub mod cards; pub mod transformers; pub mod vault; + +pub use api_models::{ + enums::{Connector, PayoutConnectors}, + payouts as payout_types, +}; +pub use common_utils::request::RequestBody; +use data_models::payments::{payment_attempt::PaymentAttempt, payment_intent::PaymentIntent}; +use diesel_models::enums; + +use crate::{ + core::{errors::RouterResult, payments::helpers}, + routes::AppState, + types::api::{self, payments}, +}; + +pub struct Oss; + +#[async_trait::async_trait] +pub trait PaymentMethodRetrieve { + async fn retrieve_payment_method( + pm_data: &Option<payments::PaymentMethodData>, + state: &AppState, + payment_intent: &PaymentIntent, + payment_attempt: &PaymentAttempt, + ) -> RouterResult<(Option<payments::PaymentMethodData>, Option<String>)>; +} + +#[async_trait::async_trait] +impl PaymentMethodRetrieve for Oss { + async fn retrieve_payment_method( + pm_data: &Option<payments::PaymentMethodData>, + state: &AppState, + payment_intent: &PaymentIntent, + payment_attempt: &PaymentAttempt, + ) -> RouterResult<(Option<payments::PaymentMethodData>, Option<String>)> { + match pm_data { + pm_opt @ Some(pm @ api::PaymentMethodData::Card(_)) => { + let payment_token = helpers::store_payment_method_data_in_vault( + state, + payment_attempt, + payment_intent, + enums::PaymentMethod::Card, + pm, + ) + .await?; + + Ok((pm_opt.to_owned(), payment_token)) + } + pm @ Some(api::PaymentMethodData::PayLater(_)) => Ok((pm.to_owned(), None)), + pm @ Some(api::PaymentMethodData::Crypto(_)) => Ok((pm.to_owned(), None)), + pm @ Some(api::PaymentMethodData::BankDebit(_)) => Ok((pm.to_owned(), None)), + pm @ Some(api::PaymentMethodData::Upi(_)) => Ok((pm.to_owned(), None)), + pm @ Some(api::PaymentMethodData::Voucher(_)) => Ok((pm.to_owned(), None)), + pm @ Some(api::PaymentMethodData::Reward) => Ok((pm.to_owned(), None)), + pm @ Some(api::PaymentMethodData::CardRedirect(_)) => Ok((pm.to_owned(), None)), + pm @ Some(api::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)), + pm_opt @ Some(pm @ api::PaymentMethodData::BankTransfer(_)) => { + let payment_token = helpers::store_payment_method_data_in_vault( + state, + payment_attempt, + payment_intent, + enums::PaymentMethod::BankTransfer, + pm, + ) + .await?; + + Ok((pm_opt.to_owned(), payment_token)) + } + pm_opt @ Some(pm @ api::PaymentMethodData::Wallet(_)) => { + let payment_token = helpers::store_payment_method_data_in_vault( + state, + payment_attempt, + payment_intent, + enums::PaymentMethod::Wallet, + pm, + ) + .await?; + + Ok((pm_opt.to_owned(), payment_token)) + } + pm_opt @ Some(pm @ api::PaymentMethodData::BankRedirect(_)) => { + let payment_token = helpers::store_payment_method_data_in_vault( + state, + payment_attempt, + payment_intent, + enums::PaymentMethod::BankRedirect, + pm, + ) + .await?; + + Ok((pm_opt.to_owned(), payment_token)) + } + _ => Ok((None, None)), + } + } +} diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 1b6d93596f1..cc84a13616d 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -18,6 +18,8 @@ use futures::future::join_all; use helpers::ApplePayData; use masking::Secret; use router_env::{instrument, tracing}; +#[cfg(feature = "olap")] +use router_types::transformers::ForeignFrom; use scheduler::{db::process_tracker::ProcessTrackerExt, errors as sch_errors, utils as pt_utils}; use time; @@ -31,12 +33,11 @@ use self::{ operations::{payment_complete_authorize, BoxedOperation, Operation}, }; use super::errors::StorageErrorExt; -#[cfg(feature = "olap")] -use crate::types::transformers::ForeignFrom; use crate::{ configs::settings::PaymentMethodTypeTokenFilter, core::{ errors::{self, CustomResult, RouterResponse, RouterResult}, + payment_methods::PaymentMethodRetrieve, utils, }, db::StorageInterface, @@ -56,7 +57,7 @@ use crate::{ #[allow(clippy::too_many_arguments)] #[instrument(skip_all, fields(payment_id, merchant_id))] -pub async fn payments_operation_core<F, Req, Op, FData>( +pub async fn payments_operation_core<F, Req, Op, FData, Ctx>( state: &AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, @@ -69,7 +70,7 @@ pub async fn payments_operation_core<F, Req, Op, FData>( where F: Send + Clone + Sync, Req: Authenticate, - Op: Operation<F, Req> + Send + Sync, + Op: Operation<F, Req, Ctx> + Send + Sync, // To create connector flow specific interface data PaymentData<F>: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, @@ -80,10 +81,11 @@ where services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse - PaymentResponse: Operation<F, FData>, + PaymentResponse: Operation<F, FData, Ctx>, FData: Send + Sync, + Ctx: PaymentMethodRetrieve, { - let operation: BoxedOperation<'_, F, Req> = Box::new(operation); + let operation: BoxedOperation<'_, F, Req, Ctx> = Box::new(operation); tracing::Span::current().record("merchant_id", merchant_account.merchant_id.as_str()); let (operation, validate_result) = operation @@ -239,7 +241,7 @@ where } #[allow(clippy::too_many_arguments)] -pub async fn payments_core<F, Res, Req, Op, FData>( +pub async fn payments_core<F, Res, Req, Op, FData, Ctx>( state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, @@ -252,31 +254,33 @@ pub async fn payments_core<F, Res, Req, Op, FData>( where F: Send + Clone + Sync, FData: Send + Sync, - Op: Operation<F, Req> + Send + Sync + Clone, + Op: Operation<F, Req, Ctx> + Send + Sync + Clone, Req: Debug + Authenticate, Res: transformers::ToResponse<Req, PaymentData<F>, Op>, // To create connector flow specific interface data PaymentData<F>: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, router_types::RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, + Ctx: PaymentMethodRetrieve, // To construct connector flow specific api dyn router_types::api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse - PaymentResponse: Operation<F, FData>, + PaymentResponse: Operation<F, FData, Ctx>, { - let (payment_data, req, customer, connector_http_status_code) = payments_operation_core( - &state, - merchant_account, - key_store, - operation.clone(), - req, - call_connector_action, - auth_flow, - header_payload, - ) - .await?; + let (payment_data, req, customer, connector_http_status_code) = + payments_operation_core::<_, _, _, _, Ctx>( + &state, + merchant_account, + key_store, + operation.clone(), + req, + call_connector_action, + auth_flow, + header_payload, + ) + .await?; Res::generate_response( Some(req), @@ -306,7 +310,7 @@ pub struct PaymentsRedirectResponseData { } #[async_trait::async_trait] -pub trait PaymentRedirectFlow: Sync { +pub trait PaymentRedirectFlow<Ctx: PaymentMethodRetrieve>: Sync { async fn call_payment_flow( &self, state: &AppState, @@ -402,7 +406,7 @@ pub trait PaymentRedirectFlow: Sync { pub struct PaymentRedirectCompleteAuthorize; #[async_trait::async_trait] -impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { +impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectCompleteAuthorize { async fn call_payment_flow( &self, state: &AppState, @@ -422,7 +426,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { }), ..Default::default() }; - payments_core::<api::CompleteAuthorize, api::PaymentsResponse, _, _, _>( + payments_core::<api::CompleteAuthorize, api::PaymentsResponse, _, _, _, Ctx>( state.clone(), merchant_account, merchant_key_store, @@ -492,7 +496,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { pub struct PaymentRedirectSync; #[async_trait::async_trait] -impl PaymentRedirectFlow for PaymentRedirectSync { +impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectSync { async fn call_payment_flow( &self, state: &AppState, @@ -517,7 +521,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync { expand_attempts: None, expand_captures: None, }; - payments_core::<api::PSync, api::PaymentsResponse, _, _, _>( + payments_core::<api::PSync, api::PaymentsResponse, _, _, _, Ctx>( state.clone(), merchant_account, merchant_key_store, @@ -552,12 +556,12 @@ impl PaymentRedirectFlow for PaymentRedirectSync { #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] -pub async fn call_connector_service<F, RouterDReq, ApiRequest>( +pub async fn call_connector_service<F, RouterDReq, ApiRequest, Ctx>( state: &AppState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connector: api::ConnectorData, - operation: &BoxedOperation<'_, F, ApiRequest>, + operation: &BoxedOperation<'_, F, ApiRequest, Ctx>, payment_data: &mut PaymentData<F>, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, @@ -573,6 +577,7 @@ where PaymentData<F>: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, + Ctx: PaymentMethodRetrieve, // To construct connector flow specific api dyn api::Connector: @@ -767,7 +772,7 @@ where router_data_res } -pub async fn call_multiple_connectors_service<F, Op, Req>( +pub async fn call_multiple_connectors_service<F, Op, Req, Ctx>( state: &AppState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, @@ -787,9 +792,10 @@ where // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, + Ctx: PaymentMethodRetrieve, // To perform router related operation for PaymentResponse - PaymentResponse: Operation<F, Req>, + PaymentResponse: Operation<F, Req, Ctx>, { let call_connectors_start_time = Instant::now(); let mut join_handlers = Vec::with_capacity(connectors.len()); @@ -969,12 +975,12 @@ where } } -async fn complete_preprocessing_steps_if_required<F, Req, Q>( +async fn complete_preprocessing_steps_if_required<F, Req, Q, Ctx>( state: &AppState, connector: &api::ConnectorData, payment_data: &PaymentData<F>, mut router_data: router_types::RouterData<F, Req, router_types::PaymentsResponseData>, - operation: &BoxedOperation<'_, F, Q>, + operation: &BoxedOperation<'_, F, Q, Ctx>, should_continue_payment: bool, ) -> RouterResult<( router_types::RouterData<F, Req, router_types::PaymentsResponseData>, @@ -1256,15 +1262,16 @@ pub enum TokenizationAction { } #[allow(clippy::too_many_arguments)] -pub async fn get_connector_tokenization_action_when_confirm_true<F, Req>( +pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, Ctx>( state: &AppState, - operation: &BoxedOperation<'_, F, Req>, + operation: &BoxedOperation<'_, F, Req, Ctx>, payment_data: &mut PaymentData<F>, validate_result: &operations::ValidateResult<'_>, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> RouterResult<(PaymentData<F>, TokenizationAction)> where F: Send + Clone, + Ctx: PaymentMethodRetrieve, { let connector = payment_data.payment_attempt.connector.to_owned(); @@ -1364,14 +1371,15 @@ where Ok(payment_data_and_tokenization_action) } -pub async fn tokenize_in_router_when_confirm_false<F, Req>( +pub async fn tokenize_in_router_when_confirm_false<F, Req, Ctx>( state: &AppState, - operation: &BoxedOperation<'_, F, Req>, + operation: &BoxedOperation<'_, F, Req, Ctx>, payment_data: &mut PaymentData<F>, validate_result: &operations::ValidateResult<'_>, ) -> RouterResult<PaymentData<F>> where F: Send + Clone, + Ctx: PaymentMethodRetrieve, { // On confirm is false and only router related let payment_data = if !is_operation_confirm(operation) { @@ -1454,15 +1462,16 @@ pub struct CustomerDetails { pub phone_country_code: Option<String>, } -pub fn if_not_create_change_operation<'a, Op, F>( +pub fn if_not_create_change_operation<'a, Op, F, Ctx>( status: storage_enums::IntentStatus, confirm: Option<bool>, current: &'a Op, -) -> BoxedOperation<'_, F, api::PaymentsRequest> +) -> BoxedOperation<'_, F, api::PaymentsRequest, Ctx> where F: Send + Clone, - Op: Operation<F, api::PaymentsRequest> + Send + Sync, - &'a Op: Operation<F, api::PaymentsRequest>, + Op: Operation<F, api::PaymentsRequest, Ctx> + Send + Sync, + &'a Op: Operation<F, api::PaymentsRequest, Ctx>, + Ctx: PaymentMethodRetrieve, { if confirm.unwrap_or(false) { Box::new(PaymentConfirm) @@ -1476,15 +1485,16 @@ where } } -pub fn is_confirm<'a, F: Clone + Send, R, Op>( +pub fn is_confirm<'a, F: Clone + Send, R, Op, Ctx>( operation: &'a Op, confirm: Option<bool>, -) -> BoxedOperation<'_, F, R> +) -> BoxedOperation<'_, F, R, Ctx> where - PaymentConfirm: Operation<F, R>, - &'a PaymentConfirm: Operation<F, R>, - Op: Operation<F, R> + Send + Sync, - &'a Op: Operation<F, R>, + PaymentConfirm: Operation<F, R, Ctx>, + &'a PaymentConfirm: Operation<F, R, Ctx>, + Op: Operation<F, R, Ctx> + Send + Sync, + &'a Op: Operation<F, R, Ctx>, + Ctx: PaymentMethodRetrieve, { if confirm.unwrap_or(false) { Box::new(&PaymentConfirm) @@ -1777,8 +1787,8 @@ where Ok(()) } -pub async fn get_connector_choice<F, Req>( - operation: &BoxedOperation<'_, F, Req>, +pub async fn get_connector_choice<F, Req, Ctx>( + operation: &BoxedOperation<'_, F, Req, Ctx>, state: &AppState, req: &Req, merchant_account: &domain::MerchantAccount, @@ -1787,6 +1797,7 @@ pub async fn get_connector_choice<F, Req>( ) -> RouterResult<Option<api::ConnectorCallType>> where F: Send + Clone, + Ctx: PaymentMethodRetrieve, { let connector_choice = operation .to_domain()? diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index d9c1d719c73..44c9b516dc5 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -36,7 +36,7 @@ use crate::{ consts::{self, BASE64_ENGINE}, core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, - payment_methods::{cards, vault}, + payment_methods::{cards, vault, PaymentMethodRetrieve}, payments, }, db::StorageInterface, @@ -936,10 +936,11 @@ where } } -pub fn response_operation<'a, F, R>() -> BoxedOperation<'a, F, R> +pub fn response_operation<'a, F, R, Ctx>() -> BoxedOperation<'a, F, R, Ctx> where F: Send + Clone, - PaymentResponse: Operation<F, R>, + Ctx: PaymentMethodRetrieve, + PaymentResponse: Operation<F, R, Ctx>, { Box::new(PaymentResponse) } @@ -1149,14 +1150,14 @@ pub async fn get_connector_default( } #[instrument(skip_all)] -pub async fn create_customer_if_not_exist<'a, F: Clone, R>( - operation: BoxedOperation<'a, F, R>, +pub async fn create_customer_if_not_exist<'a, F: Clone, R, Ctx>( + operation: BoxedOperation<'a, F, R, Ctx>, db: &dyn StorageInterface, payment_data: &mut PaymentData<F>, req: Option<CustomerDetails>, merchant_id: &str, key_store: &domain::MerchantKeyStore, -) -> CustomResult<(BoxedOperation<'a, F, R>, Option<domain::Customer>), errors::StorageError> { +) -> CustomResult<(BoxedOperation<'a, F, R, Ctx>, Option<domain::Customer>), errors::StorageError> { let request_customer_details = req .get_required_value("customer") .change_context(errors::StorageError::ValueNotFound("customer".to_owned()))?; @@ -1302,12 +1303,15 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( )) } -pub async fn make_pm_data<'a, F: Clone, R>( - operation: BoxedOperation<'a, F, R>, +pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>( + operation: BoxedOperation<'a, F, R, Ctx>, state: &'a AppState, payment_data: &mut PaymentData<F>, -) -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethodData>)> { - let request = &payment_data.payment_method_data; +) -> RouterResult<( + BoxedOperation<'a, F, R, Ctx>, + Option<api::PaymentMethodData>, +)> { + let request = &payment_data.payment_method_data.clone(); let token = payment_data.token.clone(); let hyperswitch_token = match payment_data.mandate_id { @@ -1418,89 +1422,19 @@ pub async fn make_pm_data<'a, F: Clone, R>( None => None, }) } - (pm_opt @ Some(pm @ api::PaymentMethodData::Card(_)), _) => { - if should_store_payment_method_data_in_vault( - &state.conf.temp_locker_disable_config, - payment_data.payment_attempt.connector.clone(), - enums::PaymentMethod::Card, - ) { - let parent_payment_method_token = store_in_vault_and_generate_ppmt( - state, - pm, - &payment_data.payment_intent, - &payment_data.payment_attempt, - enums::PaymentMethod::Card, - ) - .await?; - payment_data.token = Some(parent_payment_method_token); - } - Ok(pm_opt.to_owned()) - } - (pm @ Some(api::PaymentMethodData::PayLater(_)), _) => Ok(pm.to_owned()), - (pm @ Some(api::PaymentMethodData::Crypto(_)), _) => Ok(pm.to_owned()), - (pm @ Some(api::PaymentMethodData::BankDebit(_)), _) => Ok(pm.to_owned()), - (pm @ Some(api::PaymentMethodData::Upi(_)), _) => Ok(pm.to_owned()), - (pm @ Some(api::PaymentMethodData::Voucher(_)), _) => Ok(pm.to_owned()), - (pm @ Some(api::PaymentMethodData::Reward), _) => Ok(pm.to_owned()), - (pm @ Some(api::PaymentMethodData::CardRedirect(_)), _) => Ok(pm.to_owned()), - (pm @ Some(api::PaymentMethodData::GiftCard(_)), _) => Ok(pm.to_owned()), - (pm_opt @ Some(pm @ api::PaymentMethodData::BankTransfer(_)), _) => { - if should_store_payment_method_data_in_vault( - &state.conf.temp_locker_disable_config, - payment_data.payment_attempt.connector.clone(), - enums::PaymentMethod::BankTransfer, - ) { - let parent_payment_method_token = store_in_vault_and_generate_ppmt( - state, - pm, - &payment_data.payment_intent, - &payment_data.payment_attempt, - enums::PaymentMethod::BankTransfer, - ) - .await?; - - payment_data.token = Some(parent_payment_method_token); - } + (Some(_), _) => { + let payment_method_data = Ctx::retrieve_payment_method( + request, + state, + &payment_data.payment_intent, + &payment_data.payment_attempt, + ) + .await?; - Ok(pm_opt.to_owned()) - } - (pm_opt @ Some(pm @ api::PaymentMethodData::Wallet(_)), _) => { - if should_store_payment_method_data_in_vault( - &state.conf.temp_locker_disable_config, - payment_data.payment_attempt.connector.clone(), - enums::PaymentMethod::Wallet, - ) { - let parent_payment_method_token = store_in_vault_and_generate_ppmt( - state, - pm, - &payment_data.payment_intent, - &payment_data.payment_attempt, - enums::PaymentMethod::Wallet, - ) - .await?; + payment_data.token = payment_method_data.1; - payment_data.token = Some(parent_payment_method_token); - } - Ok(pm_opt.to_owned()) - } - (pm_opt @ Some(pm @ api::PaymentMethodData::BankRedirect(_)), _) => { - if should_store_payment_method_data_in_vault( - &state.conf.temp_locker_disable_config, - payment_data.payment_attempt.connector.clone(), - enums::PaymentMethod::BankRedirect, - ) { - let parent_payment_method_token = store_in_vault_and_generate_ppmt( - state, - pm, - &payment_data.payment_intent, - &payment_data.payment_attempt, - enums::PaymentMethod::BankRedirect, - ) - .await?; - payment_data.token = Some(parent_payment_method_token); - } - Ok(pm_opt.to_owned()) + Ok(payment_method_data.0) } _ => Ok(None), }?; @@ -1538,6 +1472,32 @@ pub async fn store_in_vault_and_generate_ppmt( Ok(parent_payment_method_token) } +pub async fn store_payment_method_data_in_vault( + state: &AppState, + payment_attempt: &PaymentAttempt, + payment_intent: &PaymentIntent, + payment_method: enums::PaymentMethod, + payment_method_data: &api::PaymentMethodData, +) -> RouterResult<Option<String>> { + if should_store_payment_method_data_in_vault( + &state.conf.temp_locker_disable_config, + payment_attempt.connector.clone(), + payment_method, + ) { + let parent_payment_method_token = store_in_vault_and_generate_ppmt( + state, + payment_method_data, + payment_intent, + payment_attempt, + payment_method, + ) + .await?; + + return Ok(Some(parent_payment_method_token)); + } + + Ok(None) +} pub fn should_store_payment_method_data_in_vault( temp_locker_disable_config: &TempLockerDisableConfig, option_connector: Option<String>, diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index b0c7a5ae126..d198cd562a7 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -27,7 +27,10 @@ pub use self::{ }; use super::{helpers, CustomerDetails, PaymentData}; use crate::{ - core::errors::{self, CustomResult, RouterResult}, + core::{ + errors::{self, CustomResult, RouterResult}, + payment_methods::PaymentMethodRetrieve, + }, db::StorageInterface, routes::AppState, services, @@ -38,26 +41,26 @@ use crate::{ }, }; -pub type BoxedOperation<'a, F, T> = Box<dyn Operation<F, T> + Send + Sync + 'a>; +pub type BoxedOperation<'a, F, T, Ctx> = Box<dyn Operation<F, T, Ctx> + Send + Sync + 'a>; -pub trait Operation<F: Clone, T>: Send + std::fmt::Debug { - fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F, T> + Send + Sync)> { +pub trait Operation<F: Clone, T, Ctx: PaymentMethodRetrieve>: Send + std::fmt::Debug { + fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F, T, Ctx> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("validate request interface not found for {self:?}")) } fn to_get_tracker( &self, - ) -> RouterResult<&(dyn GetTracker<F, PaymentData<F>, T> + Send + Sync)> { + ) -> RouterResult<&(dyn GetTracker<F, PaymentData<F>, T, Ctx> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("get tracker interface not found for {self:?}")) } - fn to_domain(&self) -> RouterResult<&dyn Domain<F, T>> { + fn to_domain(&self) -> RouterResult<&dyn Domain<F, T, Ctx>> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("domain interface not found for {self:?}")) } fn to_update_tracker( &self, - ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, T> + Send + Sync)> { + ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, T, Ctx> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("update tracker interface not found for {self:?}")) } @@ -80,16 +83,16 @@ pub struct ValidateResult<'a> { } #[allow(clippy::type_complexity)] -pub trait ValidateRequest<F, R> { +pub trait ValidateRequest<F, R, Ctx: PaymentMethodRetrieve> { fn validate_request<'a, 'b>( &'b self, request: &R, merchant_account: &'a domain::MerchantAccount, - ) -> RouterResult<(BoxedOperation<'b, F, R>, ValidateResult<'a>)>; + ) -> RouterResult<(BoxedOperation<'b, F, R, Ctx>, ValidateResult<'a>)>; } #[async_trait] -pub trait GetTracker<F, D, R>: Send { +pub trait GetTracker<F, D, R, Ctx: PaymentMethodRetrieve>: Send { #[allow(clippy::too_many_arguments)] async fn get_trackers<'a>( &'a self, @@ -100,11 +103,11 @@ pub trait GetTracker<F, D, R>: Send { merchant_account: &domain::MerchantAccount, mechant_key_store: &domain::MerchantKeyStore, auth_flow: services::AuthFlow, - ) -> RouterResult<(BoxedOperation<'a, F, R>, D, Option<CustomerDetails>)>; + ) -> RouterResult<(BoxedOperation<'a, F, R, Ctx>, D, Option<CustomerDetails>)>; } #[async_trait] -pub trait Domain<F: Clone, R>: Send + Sync { +pub trait Domain<F: Clone, R, Ctx: PaymentMethodRetrieve>: Send + Sync { /// This will fetch customer details, (this operation is flow specific) async fn get_or_create_customer_details<'a>( &'a self, @@ -112,7 +115,7 @@ pub trait Domain<F: Clone, R>: Send + Sync { payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, - ) -> CustomResult<(BoxedOperation<'a, F, R>, Option<domain::Customer>), errors::StorageError>; + ) -> CustomResult<(BoxedOperation<'a, F, R, Ctx>, Option<domain::Customer>), errors::StorageError>; #[allow(clippy::too_many_arguments)] async fn make_pm_data<'a>( @@ -120,7 +123,10 @@ pub trait Domain<F: Clone, R>: Send + Sync { state: &'a AppState, payment_data: &mut PaymentData<F>, storage_scheme: enums::MerchantStorageScheme, - ) -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethodData>)>; + ) -> RouterResult<( + BoxedOperation<'a, F, R, Ctx>, + Option<api::PaymentMethodData>, + )>; async fn add_task_to_process_tracker<'a>( &'a self, @@ -144,7 +150,7 @@ pub trait Domain<F: Clone, R>: Send + Sync { #[async_trait] #[allow(clippy::too_many_arguments)] -pub trait UpdateTracker<F, D, Req>: Send { +pub trait UpdateTracker<F, D, Req, Ctx: PaymentMethodRetrieve>: Send { async fn update_trackers<'b>( &'b self, db: &dyn StorageInterface, @@ -155,7 +161,7 @@ pub trait UpdateTracker<F, D, Req>: Send { mechant_key_store: &domain::MerchantKeyStore, frm_suggestion: Option<FrmSuggestion>, header_payload: api::HeaderPayload, - ) -> RouterResult<(BoxedOperation<'b, F, Req>, D)> + ) -> RouterResult<(BoxedOperation<'b, F, Req, Ctx>, D)> where F: 'b + Send; } @@ -175,10 +181,13 @@ pub trait PostUpdateTracker<F, D, R>: Send { } #[async_trait] -impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRetrieveRequest>> - Domain<F, api::PaymentsRetrieveRequest> for Op +impl< + F: Clone + Send, + Ctx: PaymentMethodRetrieve, + Op: Send + Sync + Operation<F, api::PaymentsRetrieveRequest, Ctx>, + > Domain<F, api::PaymentsRetrieveRequest, Ctx> for Op where - for<'a> &'a Op: Operation<F, api::PaymentsRetrieveRequest>, + for<'a> &'a Op: Operation<F, api::PaymentsRetrieveRequest, Ctx>, { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( @@ -189,7 +198,7 @@ where merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( - BoxedOperation<'a, F, api::PaymentsRetrieveRequest>, + BoxedOperation<'a, F, api::PaymentsRetrieveRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -225,7 +234,7 @@ where payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRetrieveRequest>, + BoxedOperation<'a, F, api::PaymentsRetrieveRequest, Ctx>, Option<api::PaymentMethodData>, )> { helpers::make_pm_data(Box::new(self), state, payment_data).await @@ -233,10 +242,13 @@ where } #[async_trait] -impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCaptureRequest>> - Domain<F, api::PaymentsCaptureRequest> for Op +impl< + F: Clone + Send, + Ctx: PaymentMethodRetrieve, + Op: Send + Sync + Operation<F, api::PaymentsCaptureRequest, Ctx>, + > Domain<F, api::PaymentsCaptureRequest, Ctx> for Op where - for<'a> &'a Op: Operation<F, api::PaymentsCaptureRequest>, + for<'a> &'a Op: Operation<F, api::PaymentsCaptureRequest, Ctx>, { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( @@ -247,7 +259,7 @@ where merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( - BoxedOperation<'a, F, api::PaymentsCaptureRequest>, + BoxedOperation<'a, F, api::PaymentsCaptureRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -271,7 +283,7 @@ where _payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsCaptureRequest>, + BoxedOperation<'a, F, api::PaymentsCaptureRequest, Ctx>, Option<api::PaymentMethodData>, )> { Ok((Box::new(self), None)) @@ -290,10 +302,13 @@ where } #[async_trait] -impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCancelRequest>> - Domain<F, api::PaymentsCancelRequest> for Op +impl< + F: Clone + Send, + Ctx: PaymentMethodRetrieve, + Op: Send + Sync + Operation<F, api::PaymentsCancelRequest, Ctx>, + > Domain<F, api::PaymentsCancelRequest, Ctx> for Op where - for<'a> &'a Op: Operation<F, api::PaymentsCancelRequest>, + for<'a> &'a Op: Operation<F, api::PaymentsCancelRequest, Ctx>, { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( @@ -304,7 +319,7 @@ where merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( - BoxedOperation<'a, F, api::PaymentsCancelRequest>, + BoxedOperation<'a, F, api::PaymentsCancelRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -329,7 +344,7 @@ where _payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsCancelRequest>, + BoxedOperation<'a, F, api::PaymentsCancelRequest, Ctx>, Option<api::PaymentMethodData>, )> { Ok((Box::new(self), None)) @@ -348,10 +363,13 @@ where } #[async_trait] -impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRejectRequest>> - Domain<F, api::PaymentsRejectRequest> for Op +impl< + F: Clone + Send, + Ctx: PaymentMethodRetrieve, + Op: Send + Sync + Operation<F, api::PaymentsRejectRequest, Ctx>, + > Domain<F, api::PaymentsRejectRequest, Ctx> for Op where - for<'a> &'a Op: Operation<F, api::PaymentsRejectRequest>, + for<'a> &'a Op: Operation<F, api::PaymentsRejectRequest, Ctx>, { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( @@ -362,7 +380,7 @@ where _merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( - BoxedOperation<'a, F, api::PaymentsRejectRequest>, + BoxedOperation<'a, F, api::PaymentsRejectRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -377,7 +395,7 @@ where _payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRejectRequest>, + BoxedOperation<'a, F, api::PaymentsRejectRequest, Ctx>, Option<api::PaymentMethodData>, )> { Ok((Box::new(self), None)) diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index 871e906ee9d..d7b3d743b95 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -11,6 +11,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, + payment_methods::PaymentMethodRetrieve, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils as core_utils, }, @@ -31,7 +32,9 @@ use crate::{ pub struct PaymentApprove; #[async_trait] -impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentApprove { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentApprove +{ #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, @@ -43,7 +46,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, PaymentData<F>, Option<CustomerDetails>, )> { @@ -262,7 +265,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa } #[async_trait] -impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentApprove { +impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx> + for PaymentApprove +{ #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, @@ -272,7 +277,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentApprove { key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -295,7 +300,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentApprove { payment_data: &mut PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, Option<api::PaymentMethodData>, )> { let (op, payment_method_data) = @@ -334,7 +339,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentApprove { } #[async_trait] -impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentApprove { +impl<F: Clone, Ctx: PaymentMethodRetrieve> + UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentApprove +{ #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, @@ -346,7 +353,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen _merchant_key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, - ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)> + ) -> RouterResult<( + BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, + PaymentData<F>, + )> where F: 'b + Send, { @@ -366,14 +376,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen } } -impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentApprove { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx> + for PaymentApprove +{ #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsRequest>, + BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, operations::ValidateResult<'a>, )> { let given_payment_id = match &request.payment_id { diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index f2964a4e48c..72006946c20 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -11,6 +11,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, + payment_methods::PaymentMethodRetrieve, payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, db::StorageInterface, @@ -29,7 +30,9 @@ use crate::{ pub struct PaymentCancel; #[async_trait] -impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for PaymentCancel { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest, Ctx> for PaymentCancel +{ #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, @@ -41,7 +44,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsCancelRequest>, + BoxedOperation<'a, F, api::PaymentsCancelRequest, Ctx>, PaymentData<F>, Option<CustomerDetails>, )> { @@ -176,7 +179,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> } #[async_trait] -impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for PaymentCancel { +impl<F: Clone, Ctx: PaymentMethodRetrieve> + UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest, Ctx> for PaymentCancel +{ #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, @@ -189,7 +194,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsCancelRequest>, + BoxedOperation<'b, F, api::PaymentsCancelRequest, Ctx>, PaymentData<F>, )> where @@ -231,14 +236,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for } } -impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCancelRequest> for PaymentCancel { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + ValidateRequest<F, api::PaymentsCancelRequest, Ctx> for PaymentCancel +{ #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsCancelRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsCancelRequest>, + BoxedOperation<'b, F, api::PaymentsCancelRequest, Ctx>, operations::ValidateResult<'a>, )> { Ok(( diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index c3b915f9d34..bd64ebac632 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -11,6 +11,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, + payment_methods::PaymentMethodRetrieve, payments::{self, helpers, operations, types::MultipleCaptureData}, }, db::StorageInterface, @@ -29,8 +30,8 @@ use crate::{ pub struct PaymentCapture; #[async_trait] -impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest> - for PaymentCapture +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest, Ctx> for PaymentCapture { #[instrument(skip_all)] async fn get_trackers<'a>( @@ -43,7 +44,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsCaptureRequest>, + BoxedOperation<'a, F, api::PaymentsCaptureRequest, Ctx>, payments::PaymentData<F>, Option<payments::CustomerDetails>, )> { @@ -236,7 +237,8 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu } #[async_trait] -impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest> +impl<F: Clone, Ctx: PaymentMethodRetrieve> + UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest, Ctx> for PaymentCapture { #[instrument(skip_all)] @@ -251,7 +253,7 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsCaptureRequest>, + BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>, payments::PaymentData<F>, )> where @@ -274,14 +276,16 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe } } -impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCaptureRequest> for PaymentCapture { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + ValidateRequest<F, api::PaymentsCaptureRequest, Ctx> for PaymentCapture +{ #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsCaptureRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsCaptureRequest>, + BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>, operations::ValidateResult<'a>, )> { Ok(( diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 1ee7bec135f..db2c9e27c9b 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -10,6 +10,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, + payment_methods::PaymentMethodRetrieve, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils as core_utils, }, @@ -30,7 +31,9 @@ use crate::{ pub struct CompleteAuthorize; #[async_trait] -impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for CompleteAuthorize { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for CompleteAuthorize +{ #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, @@ -42,7 +45,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, PaymentData<F>, Option<CustomerDetails>, )> { @@ -257,7 +260,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co } #[async_trait] -impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize { +impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx> + for CompleteAuthorize +{ #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, @@ -267,7 +272,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize { key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -290,7 +295,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize { payment_data: &mut PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, Option<api::PaymentMethodData>, )> { let (op, payment_method_data) = @@ -329,7 +334,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for CompleteAuthorize { } #[async_trait] -impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for CompleteAuthorize { +impl<F: Clone, Ctx: PaymentMethodRetrieve> + UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for CompleteAuthorize +{ #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, @@ -341,7 +348,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple _merchant_key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, - ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)> + ) -> RouterResult<( + BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, + PaymentData<F>, + )> where F: 'b + Send, { @@ -349,14 +359,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple } } -impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for CompleteAuthorize { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx> + for CompleteAuthorize +{ #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsRequest>, + BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, operations::ValidateResult<'a>, )> { let given_payment_id = match &request.payment_id { diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 2d35ef61ff6..761264e4798 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -12,6 +12,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, + payment_methods::PaymentMethodRetrieve, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, db::StorageInterface, @@ -30,7 +31,9 @@ use crate::{ #[operation(ops = "all", flow = "authorize")] pub struct PaymentConfirm; #[async_trait] -impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentConfirm { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentConfirm +{ #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, @@ -42,7 +45,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa key_store: &domain::MerchantKeyStore, auth_flow: services::AuthFlow, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, PaymentData<F>, Option<CustomerDetails>, )> { @@ -364,7 +367,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa } #[async_trait] -impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm { +impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx> + for PaymentConfirm +{ #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, @@ -374,7 +379,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm { key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -397,7 +402,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm { payment_data: &mut PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, Option<api::PaymentMethodData>, )> { let (op, payment_method_data) = @@ -436,7 +441,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm { } #[async_trait] -impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentConfirm { +impl<F: Clone, Ctx: PaymentMethodRetrieve> + UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentConfirm +{ #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, @@ -448,7 +455,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen key_store: &domain::MerchantKeyStore, frm_suggestion: Option<FrmSuggestion>, header_payload: api::HeaderPayload, - ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)> + ) -> RouterResult<( + BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, + PaymentData<F>, + )> where F: 'b + Send, { @@ -597,14 +607,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen } } -impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfirm { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx> + for PaymentConfirm +{ #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsRequest>, + BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, operations::ValidateResult<'a>, )> { helpers::validate_customer_details_in_request(request)?; diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 17d8d5f6c3d..479b0e2ccee 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -14,6 +14,7 @@ use crate::{ consts, core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, + payment_methods::PaymentMethodRetrieve, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils::{self as core_utils}, }, @@ -39,7 +40,9 @@ pub struct PaymentCreate; /// The `get_trackers` function for `PaymentsCreate` is an entrypoint for new payments /// This will create all the entities required for a new payment from the request #[async_trait] -impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentCreate { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentCreate +{ #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, @@ -51,7 +54,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa merchant_key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, PaymentData<F>, Option<CustomerDetails>, )> { @@ -231,7 +234,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await .transpose()?; - let operation = payments::if_not_create_change_operation::<_, F>( + let operation = payments::if_not_create_change_operation::<_, F, Ctx>( payment_intent.status, request.confirm, self, @@ -299,7 +302,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa } #[async_trait] -impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate { +impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx> + for PaymentCreate +{ #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, @@ -309,7 +314,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate { key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -332,7 +337,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate { payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, Option<api::PaymentMethodData>, )> { helpers::make_pm_data(Box::new(self), state, payment_data).await @@ -362,7 +367,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate { } #[async_trait] -impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentCreate { +impl<F: Clone, Ctx: PaymentMethodRetrieve> + UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentCreate +{ #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, @@ -374,7 +381,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen _merchant_key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, - ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)> + ) -> RouterResult<( + BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, + PaymentData<F>, + )> where F: 'b + Send, { @@ -444,14 +454,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen } } -impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx> + for PaymentCreate +{ #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsRequest>, + BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, operations::ValidateResult<'a>, )> { helpers::validate_customer_details_in_request(request)?; diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index 2f260ee3e0a..0ff49279f3c 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -12,6 +12,7 @@ use crate::{ consts, core::{ errors::{self, RouterResult, StorageErrorExt}, + payment_methods::PaymentMethodRetrieve, payments::{self, helpers, operations, Operation, PaymentData}, utils as core_utils, }, @@ -31,14 +32,16 @@ use crate::{ #[operation(ops = "all", flow = "verify")] pub struct PaymentMethodValidate; -impl<F: Send + Clone> ValidateRequest<F, api::VerifyRequest> for PaymentMethodValidate { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::VerifyRequest, Ctx> + for PaymentMethodValidate +{ #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::VerifyRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::VerifyRequest>, + BoxedOperation<'b, F, api::VerifyRequest, Ctx>, operations::ValidateResult<'a>, )> { let request_merchant_id = request.merchant_id.as_deref(); @@ -63,7 +66,9 @@ impl<F: Send + Clone> ValidateRequest<F, api::VerifyRequest> for PaymentMethodVa } #[async_trait] -impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for PaymentMethodValidate { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + GetTracker<F, PaymentData<F>, api::VerifyRequest, Ctx> for PaymentMethodValidate +{ #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, @@ -75,7 +80,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym _mechant_key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, ) -> RouterResult<( - BoxedOperation<'a, F, api::VerifyRequest>, + BoxedOperation<'a, F, api::VerifyRequest, Ctx>, PaymentData<F>, Option<payments::CustomerDetails>, )> { @@ -204,7 +209,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym } #[async_trait] -impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::VerifyRequest> for PaymentMethodValidate { +impl<F: Clone, Ctx: PaymentMethodRetrieve> UpdateTracker<F, PaymentData<F>, api::VerifyRequest, Ctx> + for PaymentMethodValidate +{ #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, @@ -216,7 +223,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::VerifyRequest> for PaymentM _mechant_key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, - ) -> RouterResult<(BoxedOperation<'b, F, api::VerifyRequest>, PaymentData<F>)> + ) -> RouterResult<( + BoxedOperation<'b, F, api::VerifyRequest, Ctx>, + PaymentData<F>, + )> where F: 'b + Send, { @@ -245,11 +255,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::VerifyRequest> for PaymentM } #[async_trait] -impl<F, Op> Domain<F, api::VerifyRequest> for Op +impl<F, Op, Ctx: PaymentMethodRetrieve> Domain<F, api::VerifyRequest, Ctx> for Op where F: Clone + Send, - Op: Send + Sync + Operation<F, api::VerifyRequest>, - for<'a> &'a Op: Operation<F, api::VerifyRequest>, + Op: Send + Sync + Operation<F, api::VerifyRequest, Ctx>, + for<'a> &'a Op: Operation<F, api::VerifyRequest, Ctx>, { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( @@ -260,7 +270,7 @@ where key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( - BoxedOperation<'a, F, api::VerifyRequest>, + BoxedOperation<'a, F, api::VerifyRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -283,7 +293,7 @@ where payment_data: &mut PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::VerifyRequest>, + BoxedOperation<'a, F, api::VerifyRequest, Ctx>, Option<api::PaymentMethodData>, )> { helpers::make_pm_data(Box::new(self), state, payment_data).await diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index fe52d1b89d5..c9a24b8fb84 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -10,6 +10,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, + payment_methods::PaymentMethodRetrieve, payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, db::StorageInterface, @@ -28,7 +29,9 @@ use crate::{ pub struct PaymentReject; #[async_trait] -impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsRejectRequest> for PaymentReject { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + GetTracker<F, PaymentData<F>, PaymentsRejectRequest, Ctx> for PaymentReject +{ #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, @@ -40,7 +43,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsRejectRequest> for P key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, ) -> RouterResult<( - BoxedOperation<'a, F, PaymentsRejectRequest>, + BoxedOperation<'a, F, PaymentsRejectRequest, Ctx>, PaymentData<F>, Option<CustomerDetails>, )> { @@ -162,7 +165,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsRejectRequest> for P } #[async_trait] -impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsRejectRequest> for PaymentReject { +impl<F: Clone, Ctx: PaymentMethodRetrieve> + UpdateTracker<F, PaymentData<F>, PaymentsRejectRequest, Ctx> for PaymentReject +{ #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, @@ -174,7 +179,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsRejectRequest> for Payme _mechant_key_store: &domain::MerchantKeyStore, _should_decline_transaction: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, - ) -> RouterResult<(BoxedOperation<'b, F, PaymentsRejectRequest>, PaymentData<F>)> + ) -> RouterResult<( + BoxedOperation<'b, F, PaymentsRejectRequest, Ctx>, + PaymentData<F>, + )> where F: 'b + Send, { @@ -220,14 +228,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsRejectRequest> for Payme } } -impl<F: Send + Clone> ValidateRequest<F, PaymentsRejectRequest> for PaymentReject { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, PaymentsRejectRequest, Ctx> + for PaymentReject +{ #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &PaymentsRejectRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, PaymentsRejectRequest>, + BoxedOperation<'b, F, PaymentsRejectRequest, Ctx>, operations::ValidateResult<'a>, )> { Ok(( diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index d3cb4f818f0..712515b2e87 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -11,6 +11,7 @@ use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, mandate, + payment_methods::PaymentMethodRetrieve, payments::{types::MultipleCaptureData, PaymentData}, utils as core_utils, }, diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 938441962b2..261275296f1 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -11,6 +11,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, + payment_methods::PaymentMethodRetrieve, payments::{self, helpers, operations, PaymentData}, }, db::StorageInterface, @@ -29,8 +30,8 @@ use crate::{ pub struct PaymentSession; #[async_trait] -impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> - for PaymentSession +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest, Ctx> for PaymentSession { #[instrument(skip_all)] async fn get_trackers<'a>( @@ -43,7 +44,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsSessionRequest>, + BoxedOperation<'a, F, api::PaymentsSessionRequest, Ctx>, PaymentData<F>, Option<payments::CustomerDetails>, )> { @@ -198,7 +199,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> } #[async_trait] -impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for PaymentSession { +impl<F: Clone, Ctx: PaymentMethodRetrieve> + UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest, Ctx> for PaymentSession +{ #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, @@ -211,7 +214,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsSessionRequest>, + BoxedOperation<'b, F, api::PaymentsSessionRequest, Ctx>, PaymentData<F>, )> where @@ -234,14 +237,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for } } -impl<F: Send + Clone> ValidateRequest<F, api::PaymentsSessionRequest> for PaymentSession { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + ValidateRequest<F, api::PaymentsSessionRequest, Ctx> for PaymentSession +{ #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsSessionRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsSessionRequest>, + BoxedOperation<'b, F, api::PaymentsSessionRequest, Ctx>, operations::ValidateResult<'a>, )> { //paymentid is already generated and should be sent in the request @@ -261,10 +266,13 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsSessionRequest> for Paymen } #[async_trait] -impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsSessionRequest>> - Domain<F, api::PaymentsSessionRequest> for Op +impl< + F: Clone + Send, + Ctx: PaymentMethodRetrieve, + Op: Send + Sync + Operation<F, api::PaymentsSessionRequest, Ctx>, + > Domain<F, api::PaymentsSessionRequest, Ctx> for Op where - for<'a> &'a Op: Operation<F, api::PaymentsSessionRequest>, + for<'a> &'a Op: Operation<F, api::PaymentsSessionRequest, Ctx>, { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( @@ -275,7 +283,7 @@ where key_store: &domain::MerchantKeyStore, ) -> errors::CustomResult< ( - BoxedOperation<'a, F, api::PaymentsSessionRequest>, + BoxedOperation<'a, F, api::PaymentsSessionRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -298,7 +306,7 @@ where _payment_data: &mut PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsSessionRequest>, + BoxedOperation<'b, F, api::PaymentsSessionRequest, Ctx>, Option<api::PaymentMethodData>, )> { //No payment method data for this operation diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 2d34d409979..07015810039 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -10,6 +10,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, + payment_methods::PaymentMethodRetrieve, payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, db::StorageInterface, @@ -28,7 +29,9 @@ use crate::{ pub struct PaymentStart; #[async_trait] -impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> for PaymentStart { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + GetTracker<F, PaymentData<F>, api::PaymentsStartRequest, Ctx> for PaymentStart +{ #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, @@ -40,7 +43,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f mechant_key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsStartRequest>, + BoxedOperation<'a, F, api::PaymentsStartRequest, Ctx>, PaymentData<F>, Option<CustomerDetails>, )> { @@ -171,7 +174,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f } #[async_trait] -impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for PaymentStart { +impl<F: Clone, Ctx: PaymentMethodRetrieve> + UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest, Ctx> for PaymentStart +{ #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, @@ -184,7 +189,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for P _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsStartRequest>, + BoxedOperation<'b, F, api::PaymentsStartRequest, Ctx>, PaymentData<F>, )> where @@ -194,14 +199,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for P } } -impl<F: Send + Clone> ValidateRequest<F, api::PaymentsStartRequest> for PaymentStart { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsStartRequest, Ctx> + for PaymentStart +{ #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsStartRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsStartRequest>, + BoxedOperation<'b, F, api::PaymentsStartRequest, Ctx>, operations::ValidateResult<'a>, )> { let request_merchant_id = Some(&request.merchant_id[..]); @@ -227,10 +234,13 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsStartRequest> for PaymentS } #[async_trait] -impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsStartRequest>> - Domain<F, api::PaymentsStartRequest> for Op +impl< + F: Clone + Send, + Ctx: PaymentMethodRetrieve, + Op: Send + Sync + Operation<F, api::PaymentsStartRequest, Ctx>, + > Domain<F, api::PaymentsStartRequest, Ctx> for Op where - for<'a> &'a Op: Operation<F, api::PaymentsStartRequest>, + for<'a> &'a Op: Operation<F, api::PaymentsStartRequest, Ctx>, { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( @@ -241,7 +251,7 @@ where key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( - BoxedOperation<'a, F, api::PaymentsStartRequest>, + BoxedOperation<'a, F, api::PaymentsStartRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -264,7 +274,7 @@ where payment_data: &mut PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsStartRequest>, + BoxedOperation<'a, F, api::PaymentsStartRequest, Ctx>, Option<api::PaymentMethodData>, )> { if payment_data diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 80830efd13d..6e0ef2f4bac 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -11,7 +11,11 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, - payments::{helpers, operations, types, CustomerDetails, PaymentAddress, PaymentData}, + payment_methods::PaymentMethodRetrieve, + payments::{ + helpers, operations, types as payment_types, CustomerDetails, PaymentAddress, + PaymentData, + }, }, db::StorageInterface, routes::AppState, @@ -27,31 +31,39 @@ use crate::{ #[operation(ops = "all", flow = "sync")] pub struct PaymentStatus; -impl<F: Send + Clone> Operation<F, api::PaymentsRequest> for PaymentStatus { - fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest>> { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> Operation<F, api::PaymentsRequest, Ctx> + for PaymentStatus +{ + fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, Ctx>> { Ok(self) } fn to_update_tracker( &self, - ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> - { + ) -> RouterResult< + &(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> + Send + Sync), + > { Ok(self) } } -impl<F: Send + Clone> Operation<F, api::PaymentsRequest> for &PaymentStatus { - fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest>> { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> Operation<F, api::PaymentsRequest, Ctx> + for &PaymentStatus +{ + fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, Ctx>> { Ok(*self) } fn to_update_tracker( &self, - ) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)> - { + ) -> RouterResult< + &(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> + Send + Sync), + > { Ok(*self) } } #[async_trait] -impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus { +impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx> + for PaymentStatus +{ #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, @@ -61,7 +73,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus { key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -84,7 +96,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus { payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, Option<api::PaymentMethodData>, )> { helpers::make_pm_data(Box::new(self), state, payment_data).await @@ -114,7 +126,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus { } #[async_trait] -impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentStatus { +impl<F: Clone, Ctx: PaymentMethodRetrieve> + UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentStatus +{ async fn update_trackers<'b>( &'b self, _db: &dyn StorageInterface, @@ -125,7 +139,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, - ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)> + ) -> RouterResult<( + BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, + PaymentData<F>, + )> where F: 'b + Send, { @@ -134,7 +151,9 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen } #[async_trait] -impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> for PaymentStatus { +impl<F: Clone, Ctx: PaymentMethodRetrieve> + UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest, Ctx> for PaymentStatus +{ async fn update_trackers<'b>( &'b self, _db: &dyn StorageInterface, @@ -146,7 +165,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> fo _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsRetrieveRequest>, + BoxedOperation<'b, F, api::PaymentsRetrieveRequest, Ctx>, PaymentData<F>, )> where @@ -157,8 +176,8 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> fo } #[async_trait] -impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> - for PaymentStatus +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest, Ctx> for PaymentStatus { #[instrument(skip_all)] async fn get_trackers<'a>( @@ -171,7 +190,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRetrieveRequest>, + BoxedOperation<'a, F, api::PaymentsRetrieveRequest, Ctx>, PaymentData<F>, Option<CustomerDetails>, )> { @@ -191,7 +210,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest async fn get_tracker_for_sync< 'a, F: Send + Clone, - Op: Operation<F, api::PaymentsRetrieveRequest> + 'a + Send + Sync, + Ctx: PaymentMethodRetrieve, + Op: Operation<F, api::PaymentsRetrieveRequest, Ctx> + 'a + Send + Sync, >( payment_id: &api::PaymentIdType, merchant_account: &domain::MerchantAccount, @@ -201,7 +221,7 @@ async fn get_tracker_for_sync< operation: Op, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRetrieveRequest>, + BoxedOperation<'a, F, api::PaymentsRetrieveRequest, Ctx>, PaymentData<F>, Option<CustomerDetails>, )> { @@ -282,7 +302,7 @@ async fn get_tracker_for_sync< .attach_printable_lazy(|| { format!("Error while retrieving capture list for, merchant_id: {}, payment_id: {payment_id_str}", merchant_account.merchant_id) })?; - Some(types::MultipleCaptureData::new_for_sync( + Some(payment_types::MultipleCaptureData::new_for_sync( captures, request.expand_captures, )?) @@ -388,13 +408,15 @@ async fn get_tracker_for_sync< )) } -impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRetrieveRequest> for PaymentStatus { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + ValidateRequest<F, api::PaymentsRetrieveRequest, Ctx> for PaymentStatus +{ fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsRetrieveRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsRetrieveRequest>, + BoxedOperation<'b, F, api::PaymentsRetrieveRequest, Ctx>, operations::ValidateResult<'a>, )> { let request_merchant_id = request.merchant_id.as_deref(); diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 04f36d51c2c..9e0ef76d3e7 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -11,6 +11,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, + payment_methods::PaymentMethodRetrieve, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils as core_utils, }, @@ -30,7 +31,9 @@ use crate::{ pub struct PaymentUpdate; #[async_trait] -impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentUpdate { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentUpdate +{ #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, @@ -42,7 +45,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa key_store: &domain::MerchantKeyStore, auth_flow: services::AuthFlow, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, PaymentData<F>, Option<CustomerDetails>, )> { @@ -268,7 +271,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa }) .await .transpose()?; - let next_operation: BoxedOperation<'a, F, api::PaymentsRequest> = + let next_operation: BoxedOperation<'a, F, api::PaymentsRequest, Ctx> = if request.confirm.unwrap_or(false) { Box::new(operations::PaymentConfirm) } else { @@ -350,7 +353,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa } #[async_trait] -impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate { +impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx> + for PaymentUpdate +{ #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, @@ -360,7 +365,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate { key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, Option<domain::Customer>, ), errors::StorageError, @@ -383,7 +388,7 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate { payment_data: &mut PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest>, + BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, Option<api::PaymentMethodData>, )> { helpers::make_pm_data(Box::new(self), state, payment_data).await @@ -413,7 +418,9 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate { } #[async_trait] -impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentUpdate { +impl<F: Clone, Ctx: PaymentMethodRetrieve> + UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentUpdate +{ #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, @@ -425,7 +432,10 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen _key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, - ) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)> + ) -> RouterResult<( + BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, + PaymentData<F>, + )> where F: 'b + Send, { @@ -556,14 +566,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen } } -impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate { +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx> + for PaymentUpdate +{ #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsRequest>, + BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, operations::ValidateResult<'a>, )> { helpers::validate_customer_details_in_request(request)?; diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index b647c8a97d7..530d445b50d 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -20,6 +20,7 @@ use crate::{ core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse}, + payment_methods::PaymentMethodRetrieve, payments, refunds, }, db::StorageInterface, @@ -39,7 +40,10 @@ use crate::{ const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5; const MERCHANT_ID: &str = "merchant_id"; -pub async fn payments_incoming_webhook_flow<W: types::OutgoingWebhookType>( +pub async fn payments_incoming_webhook_flow< + W: types::OutgoingWebhookType, + Ctx: PaymentMethodRetrieve, +>( state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, @@ -74,27 +78,28 @@ pub async fn payments_incoming_webhook_flow<W: types::OutgoingWebhookType>( .perform_locking_action(&state, merchant_account.merchant_id.to_string()) .await?; - let response = payments::payments_core::<api::PSync, api::PaymentsResponse, _, _, _>( - state.clone(), - merchant_account.clone(), - key_store, - payments::operations::PaymentStatus, - api::PaymentsRetrieveRequest { - resource_id: id, - merchant_id: Some(merchant_account.merchant_id.clone()), - force_sync: true, - connector: None, - param: None, - merchant_connector_details: None, - client_secret: None, - expand_attempts: None, - expand_captures: None, - }, - services::AuthFlow::Merchant, - consume_or_trigger_flow, - HeaderPayload::default(), - ) - .await; + let response = + payments::payments_core::<api::PSync, api::PaymentsResponse, _, _, _, Ctx>( + state.clone(), + merchant_account.clone(), + key_store, + payments::operations::PaymentStatus, + api::PaymentsRetrieveRequest { + resource_id: id, + merchant_id: Some(merchant_account.merchant_id.clone()), + force_sync: true, + connector: None, + param: None, + merchant_connector_details: None, + client_secret: None, + expand_attempts: None, + expand_captures: None, + }, + services::AuthFlow::Merchant, + consume_or_trigger_flow, + HeaderPayload::default(), + ) + .await; lock_action .free_lock_action(&state, merchant_account.merchant_id.to_owned()) @@ -531,7 +536,7 @@ pub async fn disputes_incoming_webhook_flow<W: types::OutgoingWebhookType>( } } -async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType>( +async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetrieve>( state: AppState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, @@ -553,7 +558,7 @@ async fn bank_transfer_webhook_flow<W: types::OutgoingWebhookType>( payment_token: payment_attempt.payment_token, ..Default::default() }; - payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>( + payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _, Ctx>( state.clone(), merchant_account.to_owned(), key_store, @@ -824,7 +829,7 @@ pub async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>( Ok(()) } -pub async fn webhooks_wrapper<W: types::OutgoingWebhookType>( +pub async fn webhooks_wrapper<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetrieve>( state: AppState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, @@ -832,7 +837,7 @@ pub async fn webhooks_wrapper<W: types::OutgoingWebhookType>( connector_name_or_mca_id: &str, body: actix_web::web::Bytes, ) -> RouterResponse<serde_json::Value> { - let (application_response, _webhooks_response_tracker) = webhooks_core::<W>( + let (application_response, _webhooks_response_tracker) = webhooks_core::<W, Ctx>( state, req, merchant_account, @@ -846,7 +851,8 @@ pub async fn webhooks_wrapper<W: types::OutgoingWebhookType>( } #[instrument(skip_all)] -pub async fn webhooks_core<W: types::OutgoingWebhookType>( + +pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetrieve>( state: AppState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, @@ -1044,7 +1050,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>( }; match flow_type { - api::WebhookFlow::Payment => payments_incoming_webhook_flow::<W>( + api::WebhookFlow::Payment => payments_incoming_webhook_flow::<W, Ctx>( state.clone(), merchant_account, key_store, @@ -1078,7 +1084,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>( .await .attach_printable("Incoming webhook flow for disputes failed")?, - api::WebhookFlow::BankTransfer => bank_transfer_webhook_flow::<W>( + api::WebhookFlow::BankTransfer => bank_transfer_webhook_flow::<W, Ctx>( state.clone(), merchant_account, key_store, diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 9d7cf220a3a..b760aa83aaa 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -10,6 +10,7 @@ use crate::{ self as app, core::{ errors::http_not_implemented, + payment_methods::{Oss, PaymentMethodRetrieve}, payments::{self, PaymentRedirectFlow}, }, openapi::examples::{ @@ -106,7 +107,7 @@ pub async fn payments_create( &req, payload, |state, auth, req| { - authorize_verify_select( + authorize_verify_select::<_, Oss>( payments::PaymentCreate, state, auth.merchant_account, @@ -160,8 +161,15 @@ pub async fn payments_start( state, &req, payload, - |state,auth, req| { - payments::payments_core::<api_types::Authorize, payment_types::PaymentsResponse, _, _, _>( + |state, auth, req| { + payments::payments_core::< + api_types::Authorize, + payment_types::PaymentsResponse, + _, + _, + _, + Oss, + >( state, auth.merchant_account, auth.key_store, @@ -227,7 +235,7 @@ pub async fn payments_retrieve( &req, payload, |state, auth, req| { - payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, auth.key_store, @@ -288,7 +296,7 @@ pub async fn payments_retrieve_with_gateway_creds( &req, payload, |state, auth, req| { - payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::PSync, payment_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, auth.key_store, @@ -354,7 +362,7 @@ pub async fn payments_update( &req, payload, |state, auth, req| { - authorize_verify_select( + authorize_verify_select::<_, Oss>( payments::PaymentUpdate, state, auth.merchant_account, @@ -430,7 +438,7 @@ pub async fn payments_confirm( &req, payload, |state, auth, req| { - authorize_verify_select( + authorize_verify_select::<_, Oss>( payments::PaymentConfirm, state, auth.merchant_account, @@ -485,7 +493,14 @@ pub async fn payments_capture( &req, payload, |state, auth, payload| { - payments::payments_core::<api_types::Capture, payment_types::PaymentsResponse, _, _, _>( + payments::payments_core::< + api_types::Capture, + payment_types::PaymentsResponse, + _, + _, + _, + Oss, + >( state, auth.merchant_account, auth.key_store, @@ -539,6 +554,7 @@ pub async fn payments_connector_session( _, _, _, + Oss, >( state, auth.merchant_account, @@ -600,7 +616,8 @@ pub async fn payments_redirect_response( &req, payload, |state, auth, req| { - payments::PaymentRedirectSync {}.handle_payments_redirect_response( + <payments::PaymentRedirectSync as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response( + &payments::PaymentRedirectSync {}, state, auth.merchant_account, auth.key_store, @@ -657,7 +674,8 @@ pub async fn payments_redirect_response_with_creds_identifier( &req, payload, |state, auth, req| { - payments::PaymentRedirectSync {}.handle_payments_redirect_response( + <payments::PaymentRedirectSync as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response( + &payments::PaymentRedirectSync {}, state, auth.merchant_account, auth.key_store, @@ -696,7 +714,9 @@ pub async fn payments_complete_authorize( &req, payload, |state, auth, req| { - payments::PaymentRedirectCompleteAuthorize {}.handle_payments_redirect_response( + + <payments::PaymentRedirectCompleteAuthorize as PaymentRedirectFlow<Oss>>::handle_payments_redirect_response( + &payments::PaymentRedirectCompleteAuthorize {}, state, auth.merchant_account, auth.key_store, @@ -745,7 +765,7 @@ pub async fn payments_cancel( &req, payload, |state, auth, req| { - payments::payments_core::<api_types::Void, payment_types::PaymentsResponse, _, _, _>( + payments::payments_core::<api_types::Void, payment_types::PaymentsResponse, _, _, _,Oss>( state, auth.merchant_account, auth.key_store, @@ -846,7 +866,7 @@ pub async fn get_filters_for_payments( ) .await } -async fn authorize_verify_select<Op>( +async fn authorize_verify_select<Op, Ctx>( operation: Op, state: app::AppState, merchant_account: domain::MerchantAccount, @@ -856,13 +876,18 @@ async fn authorize_verify_select<Op>( auth_flow: api::AuthFlow, ) -> app::core::errors::RouterResponse<api_models::payments::PaymentsResponse> where + Ctx: PaymentMethodRetrieve, Op: Sync + Clone + std::fmt::Debug - + payments::operations::Operation<api_types::Authorize, api_models::payments::PaymentsRequest> + payments::operations::Operation< + api_types::Authorize, + api_models::payments::PaymentsRequest, + Ctx, + > + payments::operations::Operation< api_types::SetupMandate, api_models::payments::PaymentsRequest, + Ctx, >, { // TODO: Change for making it possible for the flow to be inferred internally or through validation layer @@ -874,23 +899,26 @@ where match req.payment_type.unwrap_or_default() { api_models::enums::PaymentType::Normal | api_models::enums::PaymentType::RecurringMandate - | api_models::enums::PaymentType::NewMandate => payments::payments_core::< - api_types::Authorize, - payment_types::PaymentsResponse, - _, - _, - _, - >( - state, - merchant_account, - key_store, - operation, - req, - auth_flow, - payments::CallConnectorAction::Trigger, - header_payload, - ) - .await, + | api_models::enums::PaymentType::NewMandate => { + payments::payments_core::< + api_types::Authorize, + payment_types::PaymentsResponse, + _, + _, + _, + Ctx, + >( + state, + merchant_account, + key_store, + operation, + req, + auth_flow, + payments::CallConnectorAction::Trigger, + header_payload, + ) + .await + } api_models::enums::PaymentType::SetupMandate => { payments::payments_core::< api_types::SetupMandate, @@ -898,6 +926,7 @@ where _, _, _, + Ctx, >( state, merchant_account, diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs index 0bbc6add436..f9fee54d16f 100644 --- a/crates/router/src/routes/webhooks.rs +++ b/crates/router/src/routes/webhooks.rs @@ -5,6 +5,7 @@ use super::app::AppState; use crate::{ core::{ api_locking, + payment_methods::Oss, webhooks::{self, types}, }, services::{api, authentication as auth}, @@ -26,7 +27,7 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( &req, body, |state, auth, body| { - webhooks::webhooks_wrapper::<W>( + webhooks::webhooks_wrapper::<W, Oss>( state.to_owned(), &req, auth.merchant_account, diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index 744cce31327..4dbf97081a6 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -8,7 +8,10 @@ use scheduler::{ }; use crate::{ - core::payments::{self as payment_flows, operations}, + core::{ + payment_methods::Oss, + payments::{self as payment_flows, operations}, + }, db::StorageInterface, errors, routes::AppState, @@ -55,7 +58,7 @@ impl ProcessTrackerWorkflow<AppState> for PaymentsSyncWorkflow { .await?; let (payment_data, _, _, _) = - payment_flows::payments_operation_core::<api::PSync, _, _, _>( + payment_flows::payments_operation_core::<api::PSync, _, _, _, Oss>( state, merchant_account.clone(), key_store, diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 1bff639d346..551960ac138 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -4,7 +4,7 @@ mod utils; use router::{ configs, - core::payments, + core::{payment_methods::Oss, payments}, db::StorageImpl, routes, services, types::{ @@ -361,7 +361,7 @@ async fn payments_create_core() { let expected_response = services::ApplicationResponse::JsonWithHeaders((expected_response, vec![])); let actual_response = - payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>( + payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _, Oss>( state, merchant_account, key_store, @@ -531,7 +531,7 @@ async fn payments_create_core_adyen_no_redirect() { vec![], )); let actual_response = - payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>( + payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _, Oss>( state, merchant_account, key_store, diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 91b2a454eea..96ed131dc6f 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -3,7 +3,7 @@ mod utils; use router::{ - core::payments, + core::{payment_methods::Oss, payments}, db::StorageImpl, types::api::{self, enums as api_enums}, *, @@ -120,19 +120,25 @@ async fn payments_create_core() { }; let expected_response = services::ApplicationResponse::JsonWithHeaders((expected_response, vec![])); - let actual_response = - router::core::payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>( - state, - merchant_account, - key_store, - payments::PaymentCreate, - req, - services::AuthFlow::Merchant, - payments::CallConnectorAction::Trigger, - api::HeaderPayload::default(), - ) - .await - .unwrap(); + let actual_response = router::core::payments::payments_core::< + api::Authorize, + api::PaymentsResponse, + _, + _, + _, + Oss, + >( + state, + merchant_account, + key_store, + payments::PaymentCreate, + req, + services::AuthFlow::Merchant, + payments::CallConnectorAction::Trigger, + api::HeaderPayload::default(), + ) + .await + .unwrap(); assert_eq!(expected_response, actual_response); } @@ -292,18 +298,24 @@ async fn payments_create_core_adyen_no_redirect() { }, vec![], )); - let actual_response = - router::core::payments::payments_core::<api::Authorize, api::PaymentsResponse, _, _, _>( - state, - merchant_account, - key_store, - payments::PaymentCreate, - req, - services::AuthFlow::Merchant, - payments::CallConnectorAction::Trigger, - api::HeaderPayload::default(), - ) - .await - .unwrap(); + let actual_response = router::core::payments::payments_core::< + api::Authorize, + api::PaymentsResponse, + _, + _, + _, + Oss, + >( + state, + merchant_account, + key_store, + payments::PaymentCreate, + req, + services::AuthFlow::Merchant, + payments::CallConnectorAction::Trigger, + api::HeaderPayload::default(), + ) + .await + .unwrap(); assert_eq!(expected_response, actual_response); } diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs index cf71370a293..fb0ef35ef58 100644 --- a/crates/router_derive/src/macros/operation.rs +++ b/crates/router_derive/src/macros/operation.rs @@ -61,7 +61,7 @@ impl Derives { let req_type = Conversion::get_req_type(self); quote! { #[automatically_derived] - impl<F:Send+Clone> Operation<F,#req_type> for #struct_name { + impl<F:Send+Clone,Ctx: PaymentMethodRetrieve,> Operation<F,#req_type,Ctx> for #struct_name { #(#fns)* } } @@ -75,7 +75,7 @@ impl Derives { let req_type = Conversion::get_req_type(self); quote! { #[automatically_derived] - impl<F:Send+Clone> Operation<F,#req_type> for &#struct_name { + impl<F:Send+Clone,Ctx: PaymentMethodRetrieve,> Operation<F,#req_type,Ctx> for &#struct_name { #(#ref_fns)* } } @@ -138,22 +138,22 @@ impl Conversion { let req_type = Self::get_req_type(ident); match self { Self::ValidateRequest => quote! { - fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type> + Send + Sync)> { + fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type,Ctx> + Send + Sync)> { Ok(self) } }, Self::GetTracker => quote! { - fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type> + Send + Sync)> { + fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type,Ctx> + Send + Sync)> { Ok(self) } }, Self::Domain => quote! { - fn to_domain(&self) -> RouterResult<&dyn Domain<F,#req_type>> { + fn to_domain(&self) -> RouterResult<&dyn Domain<F,#req_type,Ctx>> { Ok(self) } }, Self::UpdateTracker => quote! { - fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type> + Send + Sync)> { + fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type,Ctx> + Send + Sync)> { Ok(self) } }, @@ -186,22 +186,22 @@ impl Conversion { let req_type = Self::get_req_type(ident); match self { Self::ValidateRequest => quote! { - fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type> + Send + Sync)> { + fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest<F,#req_type,Ctx> + Send + Sync)> { Ok(*self) } }, Self::GetTracker => quote! { - fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type> + Send + Sync)> { + fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F,PaymentData<F>,#req_type,Ctx> + Send + Sync)> { Ok(*self) } }, Self::Domain => quote! { - fn to_domain(&self) -> RouterResult<&(dyn Domain<F,#req_type>)> { + fn to_domain(&self) -> RouterResult<&(dyn Domain<F,#req_type,Ctx>)> { Ok(*self) } }, Self::UpdateTracker => quote! { - fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type> + Send + Sync)> { + fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<F,PaymentData<F>,#req_type,Ctx> + Send + Sync)> { Ok(*self) } },
2023-10-03T13:46:00Z
## 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 includes changes for adding a new generic, context, which will be passed during api call (server_wrap) to call the related implementation depending on context ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
f364a069b90dd63a28cf25457b2cd4fda0829a8b
juspay/hyperswitch
juspay__hyperswitch-2344
Bug: [FEATURE]: [PayU] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs index c43e59ac76c..9a2e14215c7 100644 --- a/crates/router/src/connector/payu/transformers.rs +++ b/crates/router/src/connector/payu/transformers.rs @@ -194,12 +194,17 @@ impl<F, T> Ok(Self { status: enums::AttemptStatus::from(item.response.status.status_code), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.order_id.clone(), + ), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: item + .response + .ext_order_id + .or(Some(item.response.order_id)), }), amount_captured: None, ..item.data @@ -326,12 +331,17 @@ impl<F, T> Ok(Self { status: enums::AttemptStatus::from(item.response.status.status_code.clone()), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.order_id.clone(), + ), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: item + .response + .ext_order_id + .or(Some(item.response.order_id)), }), amount_captured: None, ..item.data @@ -461,7 +471,10 @@ impl<F, T> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: order + .ext_order_id + .clone() + .or(Some(order.order_id.clone())), }), amount_captured: Some( order
2023-10-04T16:32:38Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Fixes #2344 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Fixes #2344 ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
b5cc7483f99dcd995b9022d21c94f2f9710ea7fe
juspay/hyperswitch
juspay__hyperswitch-2345
Bug: [FEATURE]: [PowerTranz] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index 4703a81f30f..4032f8019b0 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -123,7 +123,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest .to_string(), three_d_secure, source, - order_identifier: item.payment_id.clone(), + order_identifier: item.connector_request_reference_id.clone(), // billing_address, // shipping_address, extended_data, @@ -239,6 +239,7 @@ pub struct PowertranzBaseResponse { iso_response_code: String, redirect_data: Option<String>, response_message: String, + order_identifier: String, } impl ForeignFrom<(u8, bool, bool)> for enums::AttemptStatus { @@ -297,7 +298,7 @@ impl<F, T> let connector_transaction_id = item .response .original_trxn_identifier - .unwrap_or(item.response.transaction_identifier); + .unwrap_or(item.response.transaction_identifier.clone()); let redirection_data = item.response .redirect_data @@ -311,7 +312,7 @@ impl<F, T> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.order_identifier), }), Err, );
2023-10-02T08:23:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### 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). --> Fixes #2345 ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
89cb63be3328010d26b5f6322449fc50e80593e4
juspay/hyperswitch
juspay__hyperswitch-2347
Bug: [FEATURE]: [Shift4] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 23c91e48d8c..0dd3b858349 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -717,6 +717,7 @@ impl<T, F> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { + let connector_id = types::ResponseId::ConnectorTransactionId(item.response.id.clone()); Ok(Self { status: enums::AttemptStatus::foreign_from(( item.response.captured, @@ -727,7 +728,7 @@ impl<T, F> item.response.status, )), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: connector_id, redirection_data: item .response .flow @@ -737,7 +738,7 @@ impl<T, F> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.id), }), ..item.data })
2023-10-08T00:13:23Z
## 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 --> fixes #2316 ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
31431e41357d4d3d12668fa0d678cce0b3d86611
juspay/hyperswitch
juspay__hyperswitch-2342
Bug: [FEATURE]: [OpenNode] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs index 70a50e1b922..aa3fae3a516 100644 --- a/crates/router/src/connector/opennode/transformers.rs +++ b/crates/router/src/connector/opennode/transformers.rs @@ -78,6 +78,7 @@ pub struct OpennodePaymentsResponseData { id: String, hosted_checkout_url: String, status: OpennodePaymentStatus, + order_id: Option<String>, } //TODO: Fill the struct with respective fields @@ -114,7 +115,7 @@ impl<F, T> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: item.response.data.order_id, }) } else { Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { @@ -125,7 +126,7 @@ impl<F, T> "Please check the transaction in opennode dashboard and resolve manually" .to_string(), }), - connector_response_reference_id: None, + connector_response_reference_id: item.response.data.order_id, }) }; Ok(Self {
2023-10-02T13:56:34Z
## 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 --> ### 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 #2342. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
f720aecf1fb676cec71e636b877a46f9791d713a
juspay/hyperswitch
juspay__hyperswitch-2341
Bug: [FEATURE]: [Opayo] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index e6c3d90fa4f..d828232dbc1 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -86,6 +86,7 @@ impl From<OpayoPaymentStatus> for enums::AttemptStatus { pub struct OpayoPaymentsResponse { status: OpayoPaymentStatus, id: String, + transaction_id: String, } impl<F, T> @@ -99,12 +100,14 @@ impl<F, T> Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.transaction_id.clone(), + ), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.transaction_id), }), ..item.data })
2023-10-02T18:54:39Z
## 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 --> opayo uses [transaction_Id ](https://developer-eu.elavon.com/docs/opayo/spec/api-reference#operation/createTransaction) filled the connector_response_reference_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). --> Fixes #2341 ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
688557ef95826622fe87a4de1dfbc09446496686
juspay/hyperswitch
juspay__hyperswitch-2343
Bug: [FEATURE]: [Payeezy] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index d6c22ba67c3..98e8ea12c00 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -67,6 +67,7 @@ pub struct PayeezyPaymentsRequest { pub currency_code: String, pub credit_card: PayeezyPaymentMethod, pub stored_credentials: Option<StoredCredentials>, + pub reference: String, } #[derive(Serialize, Debug)] @@ -118,6 +119,7 @@ fn get_card_specific_payment_data( currency_code, credit_card, stored_credentials, + reference: item.connector_request_reference_id.clone(), }) } fn get_transaction_type_and_stored_creds( @@ -252,6 +254,7 @@ pub struct PayeezyPaymentsResponse { pub gateway_resp_code: String, pub gateway_message: String, pub stored_credentials: Option<PaymentsStoredCredentials>, + pub reference: Option<String>, } #[derive(Debug, Deserialize)] @@ -354,13 +357,17 @@ impl<F, T> status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transaction_id, + item.response.transaction_id.clone(), ), redirection_data: None, mandate_reference, connector_metadata: metadata, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some( + item.response + .reference + .unwrap_or(item.response.transaction_id), + ), }), ..item.data })
2023-10-01T19:11: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 --> Add `connector_response_reference_id` support for Payeezy - Used `transaction_id` as the reference id, while implementing this! Resolves #2343 and resolves #2312. ### 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? Need help testing! <!-- 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
89cb63be3328010d26b5f6322449fc50e80593e4
juspay/hyperswitch
juspay__hyperswitch-2340
Bug: [FEATURE]: [Nuvei] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 21b72955414..cf7d480e0c1 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1294,7 +1294,7 @@ where Ok(types::PaymentsResponseData::TransactionResponse { resource_id: response .transaction_id - .map_or(response.order_id, Some) // For paypal there will be no transaction_id, only order_id will be present + .map_or(response.order_id.clone(), Some) // For paypal there will be no transaction_id, only order_id will be present .map(types::ResponseId::ConnectorTransactionId) .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, redirection_data, @@ -1318,7 +1318,7 @@ where None }, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: response.order_id, }) }, ..item.data
2023-10-01T18:46:13Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Nuvei is using just the [order id](https://developer.nuvei.com/chapter-4-payment-page) to track the transaction. ### 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 #2340 ## 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)? --> I wasn't able to test it on my machine due to ram restrictions. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
89cb63be3328010d26b5f6322449fc50e80593e4
juspay/hyperswitch
juspay__hyperswitch-2339
Bug: [FEATURE]: [Noon] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index d7dc832b445..6c3084a75e4 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -356,6 +356,7 @@ pub struct NoonPaymentsOrderResponse { id: u64, error_code: u64, error_message: Option<String>, + reference: Option<String>, } #[derive(Debug, Serialize, Deserialize)] @@ -410,14 +411,20 @@ impl<F, T> reason: Some(error_message), status_code: item.http_code, }), - _ => Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(order.id.to_string()), - redirection_data, - mandate_reference, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: None, - }), + _ => { + let connector_response_reference_id = + order.reference.or(Some(order.id.to_string())); + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + order.id.to_string(), + ), + redirection_data, + mandate_reference, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id, + }) + } }, ..item.data }) @@ -660,6 +667,7 @@ impl From<NoonWebhookObject> for NoonPaymentsResponse { //For successful payments Noon Always populates error_code as 0. error_code: 0, error_message: None, + reference: None, }, checkout_data: None, subscription: None,
2023-10-04T10:01:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description I have added `reference` that's sent to noon payments order to the `TransactionResponse` in `transformer.rs` of noon that's present in the `connector` directory. https://github.com/juspay/hyperswitch/blob/main/crates/router/src/connector/noon/transformers.rs ## Motivation and Context Closes #2339 ## Checklist - [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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ab2cde799371a66eb045cf8b20431b3b108dac44
juspay/hyperswitch
juspay__hyperswitch-2338
Bug: [FEATURE]: [NMI] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 5b486aae600..926f2c300d2 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -727,7 +727,7 @@ impl<T> Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transactionid.to_owned(), + item.response.transactionid.clone(), ), redirection_data: None, mandate_reference: None, @@ -783,7 +783,7 @@ impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>> Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transactionid.to_owned(), + item.response.transactionid.clone(), ), redirection_data: None, mandate_reference: None, @@ -833,7 +833,7 @@ impl<T> Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transactionid.to_owned(), + item.response.transactionid.clone(), ), redirection_data: None, mandate_reference: None,
2023-10-26T17:24:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Make any Payment for connector NMI and see that you are getting "reference_id" field in the payments response of hyperswitch. It should not be 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8ac4c205e8876ce596ff9a729e1f034360624ec2
juspay/hyperswitch
juspay__hyperswitch-2337
Bug: [FEATURE]: [Nexi Nets] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 5949e48ae18..7b2a41cfb0b 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -364,7 +364,7 @@ impl<F, T> mandate_reference, connector_metadata: Some(connector_metadata), network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.order_id), }), ..item.data }) @@ -425,7 +425,7 @@ impl<F, T> let transaction_id = Some(item.response.transaction_id.clone()); let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata { transaction_id, - order_id: Some(item.response.order.order_id), + order_id: Some(item.response.order.order_id.clone()), psync_flow: item.response.transaction_type.clone(), }) .into_report() @@ -447,7 +447,7 @@ impl<F, T> mandate_reference: None, connector_metadata: Some(connector_metadata), network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.order.order_id), }), ..item.data })
2023-10-10T14:22:43Z
## Type of Change - [x] New feature ## Description The `connector_response_reference_id` parameter has been set for the Nexi Nets Payment Solutions for uniform reference and transaction tracking. ### File Changes - [x] This PR modifies the Nexi Nets Transformers file. **Location- router/src/connector/nexinets/transformers.rs** ## Motivation and Context This PR was raised so that it Fixes #2337 ## How did you test it? - **I ran the following command, and all the errors were addressed properly, and the build was successful.** ```bash cargo clippy --all-features ``` ![build](https://github.com/juspay/hyperswitch/assets/47860497/19ebeb9b-a14a-4213-9528-262c8fefecb4) - The code changes were formatted with the following command to fix styling issues. ```bash cargo +nightly fmt ``` ## 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
3854d58270937ac4d2e5901eeb215bc19fffc838
juspay/hyperswitch
juspay__hyperswitch-2336
Bug: [FEATURE]: [Multisafepay] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 2fa8a4c9030..dfc7bad277d 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -530,7 +530,9 @@ impl<F, T> Ok(Self { status: enums::AttemptStatus::from(status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.data.order_id), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.data.order_id.clone(), + ), redirection_data, mandate_reference: item .response @@ -543,7 +545,7 @@ impl<F, T> }), connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.data.order_id.clone()), }), ..item.data })
2023-10-04T16:17:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Updated the `connector_response_reference_id` value from the response. closes #2336 ### 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 - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as payment_id, attempt_id, and connector_transaction_id for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ## 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` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
65ca5f12da54715e5db785d122e2ec9714147c68
juspay/hyperswitch
juspay__hyperswitch-2335
Bug: [FEATURE]: [Mollie] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs index 3c23c9f1d39..56f280d288a 100644 --- a/crates/router/src/connector/mollie/transformers.rs +++ b/crates/router/src/connector/mollie/transformers.rs @@ -590,7 +590,7 @@ pub struct RefundResponse { status: MollieRefundStatus, description: Option<String>, metadata: serde_json::Value, - payment_id: String, + connector_response_reference_id: String, #[serde(rename = "_links")] links: Links, }
2023-10-26T04:17:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Motivation can be found https://github.com/juspay/hyperswitch/issues/2335 ## 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)? --> Make any Payment for connector Mollie and see that you are getting "reference_id" field in the payments response of hyperswitch. It should not be 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8e484ddab8d3f4463299c7f7e8ce75b8dd628599
juspay/hyperswitch
juspay__hyperswitch-2333
Bug: [FEATURE]: [Iatapay] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 39dfd61b9a3..9d4ecdff197 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -212,10 +212,14 @@ impl<F, T> item: types::ResponseRouterData<F, IatapayPaymentsResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { let form_fields = HashMap::new(); - let id = match item.response.iata_payment_id { + let id = match item.response.iata_payment_id.clone() { Some(s) => types::ResponseId::ConnectorTransactionId(s), None => types::ResponseId::NoResponseId, }; + let connector_response_reference_id = item + .response + .merchant_payment_id + .or(item.response.iata_payment_id); Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: item.response.checkout_methods.map_or( @@ -225,7 +229,7 @@ impl<F, T> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: connector_response_reference_id.clone(), }), |checkout_methods| { Ok(types::PaymentsResponseData::TransactionResponse { @@ -238,7 +242,7 @@ impl<F, T> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: connector_response_reference_id.clone(), }) }, ),
2023-10-10T07:58:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Adressess issue #2333 : Implement `connector_response_reference_id ` as reference to connector for Iatapay - Modified the file `hyperswitch/crates/router/src/connector/iatapay/transformers.rs` - Rebased with changes from [https://github.com/juspay/hyperswitch/commit/67cf33d0894f337839bb35b2a87d3807085e6672](url) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ x] I formatted the code `cargo +nightly fmt --all` - [ x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d9fb5d4a52f44809ab4a1576a99e97b4c8b8c41b
juspay/hyperswitch
juspay__hyperswitch-2330
Bug: [FEATURE]: [Forte] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index dcc8b97788d..bc7c55c4f87 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -259,7 +259,7 @@ impl<F, T> auth_id: item.response.authorization_code, })), network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(transaction_id.to_string()), }), ..item.data }) @@ -306,7 +306,7 @@ impl<F, T> auth_id: item.response.authorization_code, })), network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(transaction_id.to_string()), }), ..item.data }) @@ -362,19 +362,18 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<ForteCaptureResponse>> fn try_from( item: types::PaymentsCaptureResponseRouterData<ForteCaptureResponse>, ) -> Result<Self, Self::Error> { + let transaction_id = &item.response.transaction_id; Ok(Self { status: enums::AttemptStatus::from(item.response.response.response_code), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transaction_id, - ), + resource_id: types::ResponseId::ConnectorTransactionId(transaction_id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: Some(serde_json::json!(ForteMeta { auth_id: item.response.authorization_code, })), network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.transaction_id.to_string()), }), amount_captured: None, ..item.data @@ -441,7 +440,7 @@ impl<F, T> auth_id: item.response.authorization_code, })), network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(transaction_id.to_string()), }), ..item.data })
2023-10-05T07:22:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Addreses issue #2330 Updated `connector_response_reference_id` to use `transaction_id` from Forte response. Forte 'POST' Payment Docs -> https://restdocs.forte.net/#c35427927-d955-4087-88d3-f99413ed91c2 ### 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)? --> This code was tested manually, I was able to verify the updated `connector_response_reference_id` in the response to the POST request to create a payment. <img width="1382" alt="forte_response" src="https://github.com/juspay/hyperswitch/assets/29712119/ffd4859c-e23d-48bb-800d-7acb25b0ebcc"> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
bb2ba0815330578295de8036ea1a5e6d66a36277
juspay/hyperswitch
juspay__hyperswitch-2329
Bug: [FEATURE]: [Fiserv] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index 6c6c346dccc..c9c2f0c4087 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -315,7 +315,9 @@ impl<F, T> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some( + gateway_resp.transaction_processing_details.order_id, + ), }), ..item.data }) @@ -350,7 +352,13 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, FiservSyncResponse, T, types::Pa mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some( + gateway_resp + .gateway_response + .transaction_processing_details + .order_id + .clone(), + ), }), ..item.data })
2023-10-07T15:44:04Z
Update connector_response_reference_id to use gateway_resp.transaction_processing_details.order_id in fiserv transformers. Fixes #2329 ## 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 --> ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3f1e7c2152a839a6fe69f60b906277ca831e7611
juspay/hyperswitch
juspay__hyperswitch-2328
Bug: [FEATURE]: [Dlocal] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index e6db1503e59..8558836372e 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -250,6 +250,7 @@ pub struct DlocalPaymentsResponse { status: DlocalPaymentStatus, id: String, three_dsecure: Option<ThreeDSecureResData>, + order_id: String, } impl<F, T> @@ -269,12 +270,12 @@ impl<F, T> }); let response = types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id.clone()), redirection_data, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.order_id.clone()), }; Ok(Self { status: enums::AttemptStatus::from(item.response.status), @@ -288,6 +289,7 @@ impl<F, T> pub struct DlocalPaymentsSyncResponse { status: DlocalPaymentStatus, id: String, + order_id: String, } impl<F, T> @@ -307,12 +309,14 @@ impl<F, T> Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.order_id.clone(), + ), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.order_id.clone()), }), ..item.data }) @@ -323,6 +327,7 @@ impl<F, T> pub struct DlocalPaymentsCaptureResponse { status: DlocalPaymentStatus, id: String, + order_id: String, } impl<F, T> @@ -342,12 +347,14 @@ impl<F, T> Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.order_id.clone(), + ), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.order_id.clone()), }), ..item.data }) @@ -356,7 +363,7 @@ impl<F, T> pub struct DlocalPaymentsCancelResponse { status: DlocalPaymentStatus, - id: String, + order_id: String, } impl<F, T> @@ -376,12 +383,14 @@ impl<F, T> Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.order_id.clone(), + ), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.order_id.clone()), }), ..item.data })
2023-10-04T11:16:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> I have populated the 'id' which is provided as a payment-specific ID in their response to then be populated as 'connector_reference_id'. As per the docs they don't require a payment reference ID in their payment requests. So populated the existing id. ![dlocal1](https://github.com/juspay/hyperswitch/assets/130867468/8ac1f873-c20e-4c82-aa0b-b45604159452) ### 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 you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> If it fixes an open issue, please link to the issue here. It fixes an open issue . Closes #2328 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d177b4d94f08fb8ef44b5c07ec1bdc771baa016d
juspay/hyperswitch
juspay__hyperswitch-2327
Bug: [FEATURE]: [Cybersource] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 106ce2e3c29..3558f752841 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -275,6 +275,13 @@ pub struct CybersourcePaymentsResponse { id: String, status: CybersourcePaymentStatus, error_information: Option<CybersourceErrorInformation>, + client_reference_information: Option<ClientReferenceInformation>, +} + +#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ClientReferenceInformation { + code: Option<String>, } #[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)] @@ -313,12 +320,18 @@ impl<F, T> status_code: item.http_code, }), _ => Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.id.clone(), + ), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: item + .response + .client_reference_information + .map(|cref| cref.code) + .unwrap_or(Some(item.response.id)), }), }, ..item.data @@ -331,6 +344,7 @@ impl<F, T> pub struct CybersourceTransactionResponse { id: String, application_information: ApplicationInformation, + client_reference_information: Option<ClientReferenceInformation>, } #[derive(Debug, Deserialize)] @@ -378,12 +392,16 @@ impl<F, T> item.response.application_information.status.into(), ), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: item + .response + .client_reference_information + .map(|cref| cref.code) + .unwrap_or(Some(item.response.id)), }), ..item.data })
2023-10-05T19:02:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Use connector_response_reference_id as reference to merchant for Cybersource Fixes #2327 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context fixes #2327 <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
503823408b782968fb59f6ff5d7df417b9aa7dbe
juspay/hyperswitch
juspay__hyperswitch-2331
Bug: [FEATURE]: [GlobalPayments] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/Cargo.lock b/Cargo.lock index 082bb476dec..fff48158ded 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -422,45 +422,6 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8868f09ff8cea88b079da74ae569d9b8c62a23c68c746240b704ee6f7525c89c" -[[package]] -name = "asn1-rs" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f6fd5ddaf0351dff5b8da21b2fb4ff8e08ddd02857f0bf69c47639106c0fff0" -dependencies = [ - "asn1-rs-derive", - "asn1-rs-impl", - "displaydoc", - "nom", - "num-traits", - "rusticata-macros", - "thiserror", - "time 0.3.22", -] - -[[package]] -name = "asn1-rs-derive" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "726535892e8eae7e70657b4c8ea93d26b8553afb1ce617caee529ef96d7dee6c" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", - "synstructure", -] - -[[package]] -name = "asn1-rs-impl" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2777730b2039ac0f95f093556e61b6d26cebed5393ca6f152717777cec3a42ed" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "assert-json-diff" version = "2.0.2" @@ -533,7 +494,7 @@ dependencies = [ "log", "parking", "polling", - "rustix 0.37.20", + "rustix", "slab", "socket2", "waker-fn", @@ -567,7 +528,7 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -578,7 +539,7 @@ checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -1189,9 +1150,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.4.0" +version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" +checksum = "6dbe3c979c178231552ecba20214a8272df4e09f232a87aef4320cf06539aded" [[package]] name = "blake3" @@ -1251,9 +1212,9 @@ checksum = "2c676a478f63e9fa2dd5368a42f28bba0d6c560b775f38583c8bbaa7fcd67c9c" [[package]] name = "bytemuck" -version = "1.14.0" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "374d28ec25809ee0e23827c2ab573d729e293f281dfe393500e7ad618baa61c6" +checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea" [[package]] name = "byteorder" @@ -1424,7 +1385,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -1464,7 +1425,6 @@ dependencies = [ "fake", "futures", "hex", - "http", "masking", "md5", "nanoid", @@ -1474,7 +1434,6 @@ dependencies = [ "quick-xml", "rand 0.8.5", "regex", - "reqwest", "ring", "router_env", "serde", @@ -1482,7 +1441,6 @@ dependencies = [ "serde_urlencoded", "signal-hook", "signal-hook-tokio", - "strum 0.24.1", "test-case", "thiserror", "time 0.3.22", @@ -1693,7 +1651,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -1715,7 +1673,7 @@ checksum = "29a358ff9f12ec09c3e61fef9b5a9902623a695a46a917b07f269bff1445611a" dependencies = [ "darling_core 0.20.1", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -1731,12 +1689,6 @@ dependencies = [ "parking_lot_core", ] -[[package]] -name = "data-encoding" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2e66c9d817f1720209181c316d28635c050fa304f9c79e47a520882661b7308" - [[package]] name = "data_models" version = "0.1.0" @@ -1746,7 +1698,6 @@ dependencies = [ "common_enums", "common_utils", "error-stack", - "masking", "serde", "serde_json", "strum 0.25.0", @@ -1783,20 +1734,6 @@ dependencies = [ "byteorder", ] -[[package]] -name = "der-parser" -version = "8.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbd676fbbab537128ef0278adb5576cf363cff6aa22a7b24effe97347cfab61e" -dependencies = [ - "asn1-rs", - "displaydoc", - "nom", - "num-bigint", - "num-traits", - "rusticata-macros", -] - [[package]] name = "derive_deref" version = "1.1.1" @@ -1827,7 +1764,7 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7a532c1f99a0f596f6960a60d1e119e91582b24b39e2d83a190e61262c3ef0c" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.3.2", "byteorder", "diesel_derives", "itoa", @@ -1846,7 +1783,7 @@ dependencies = [ "diesel_table_macro_syntax", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -1879,7 +1816,7 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc5557efc453706fed5e4fa85006fe9817c224c3f480a34c7e5959fd700921c5" dependencies = [ - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -1919,17 +1856,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "displaydoc" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.32", -] - [[package]] name = "dlv-list" version = "0.3.0" @@ -2336,7 +2262,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -2781,12 +2707,13 @@ checksum = "12b6ee2129af8d4fb011108c73d99a1b83a85977f23b82460c0ae2e25bb4b57f" [[package]] name = "is-terminal" -version = "0.4.9" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" +checksum = "adcf93614601c8129ddf72e2d5633df827ba6551541c6d8c59520a371475be1f" dependencies = [ "hermit-abi 0.3.1", - "rustix 0.38.3", + "io-lifetimes", + "rustix", "windows-sys 0.48.0", ] @@ -2945,12 +2872,6 @@ version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" -[[package]] -name = "linux-raw-sys" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a9bad9f94746442c783ca431b22403b519cd7fbeed0533fdd6328b2f2212128" - [[package]] name = "literally" version = "0.1.3" @@ -3305,15 +3226,6 @@ dependencies = [ "libc", ] -[[package]] -name = "oid-registry" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bedf36ffb6ba96c2eb7144ef6270557b52e54b20c0a8e1eb2ff99a6c6959bff" -dependencies = [ - "asn1-rs", -] - [[package]] name = "once_cell" version = "1.18.0" @@ -3349,7 +3261,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -3563,7 +3475,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -3614,7 +3526,7 @@ checksum = "39407670928234ebc5e6e580247dd567ad73a3578460c5990f9503df207e8f07" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -4175,7 +4087,6 @@ dependencies = [ "nanoid", "num_cpus", "once_cell", - "openssl", "qrcode", "rand 0.8.5", "redis_interface", @@ -4208,7 +4119,6 @@ dependencies = [ "utoipa-swagger-ui", "uuid", "wiremock", - "x509-parser", ] [[package]] @@ -4282,7 +4192,7 @@ dependencies = [ "quote", "rust-embed-utils", "shellexpand", - "syn 2.0.32", + "syn 2.0.29", "walkdir", ] @@ -4321,15 +4231,6 @@ dependencies = [ "semver", ] -[[package]] -name = "rusticata-macros" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" -dependencies = [ - "nom", -] - [[package]] name = "rustix" version = "0.37.20" @@ -4340,20 +4241,7 @@ dependencies = [ "errno", "io-lifetimes", "libc", - "linux-raw-sys 0.3.8", - "windows-sys 0.48.0", -] - -[[package]] -name = "rustix" -version = "0.38.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac5ffa1efe7548069688cd7028f32591853cd7b5b756d41bcffd2353e4fc75b4" -dependencies = [ - "bitflags 2.4.0", - "errno", - "libc", - "linux-raw-sys 0.4.7", + "linux-raw-sys", "windows-sys 0.48.0", ] @@ -4540,31 +4428,31 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.188" +version = "1.0.164" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" +checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.188" +version = "1.0.164" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" +checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] name = "serde_json" -version = "1.0.106" +version = "1.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cc66a619ed80bf7a0f6b17dd063a84b88f6dea1813737cf469aef1d081142c2" +checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" dependencies = [ - "indexmap 2.0.0", + "indexmap 1.9.3", "itoa", "ryu", "serde", @@ -4618,7 +4506,7 @@ checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -4667,7 +4555,7 @@ dependencies = [ "darling 0.20.1", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -4692,7 +4580,7 @@ checksum = "91d129178576168c589c9ec973feedf7d3126c01ac2bf08795109aa35b69fb8f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -4864,7 +4752,6 @@ dependencies = [ "ring", "router_env", "serde", - "serde_json", "thiserror", "tokio", ] @@ -4925,7 +4812,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -4947,9 +4834,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.32" +version = "2.0.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "239814284fd6f1a4ffe4ca893952cdd93c224b6a1571c9a9eadd670295c0c9e2" +checksum = "c324c494eba9d92503e6f1ef2e6df781e78f6a7705a0202d9801b198807d518a" dependencies = [ "proc-macro2", "quote", @@ -4962,18 +4849,6 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", - "unicode-xid", -] - [[package]] name = "tagptr" version = "0.2.0" @@ -4990,7 +4865,7 @@ dependencies = [ "cfg-if", "fastrand", "redox_syscall 0.3.5", - "rustix 0.37.20", + "rustix", "windows-sys 0.48.0", ] @@ -5120,7 +4995,7 @@ checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -5234,7 +5109,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -5581,12 +5456,6 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" -[[package]] -name = "unicode-xid" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c" - [[package]] name = "unidecode" version = "0.3.0" @@ -5644,7 +5513,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", ] [[package]] @@ -5783,7 +5652,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", "wasm-bindgen-shared", ] @@ -5817,7 +5686,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.29", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -6085,23 +5954,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "x509-parser" -version = "0.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7069fba5b66b9193bd2c5d3d4ff12b839118f6bcbef5328efafafb5395cf63da" -dependencies = [ - "asn1-rs", - "data-encoding", - "der-parser", - "lazy_static", - "nom", - "oid-registry", - "rusticata-macros", - "thiserror", - "time 0.3.22", -] - [[package]] name = "xmlparser" version = "0.13.5" diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 1801f108f2e..9da548baf24 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -80,8 +80,10 @@ impl ConnectorValidation for Adyen { ) -> 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 => Err( + enums::CaptureMethod::Automatic + | enums::CaptureMethod::Manual + | enums::CaptureMethod::ManualMultiple => Ok(()), + enums::CaptureMethod::Scheduled => Err( connector_utils::construct_not_implemented_error_report(capture_method, self.id()), ), } @@ -204,6 +206,7 @@ impl data: data.clone(), http_code: res.status_code, }, + None, false, )) .change_context(errors::ConnectorError::ResponseHandlingFailed) @@ -468,15 +471,18 @@ impl .response .parse_struct("AdyenPaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - let is_manual_capture = - data.request.capture_method == Some(storage_enums::CaptureMethod::Manual); + let is_multiple_capture_sync = match data.request.sync_type { + types::SyncRequestType::MultipleCaptureSync(_) => true, + types::SyncRequestType::SinglePaymentSync => false, + }; types::RouterData::try_from(( types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }, - is_manual_capture, + data.request.capture_method, + is_multiple_capture_sync, )) .change_context(errors::ConnectorError::ResponseHandlingFailed) } @@ -496,6 +502,12 @@ impl reason: None, }) } + + fn get_multiple_capture_sync_method( + &self, + ) -> CustomResult<services::CaptureSyncMethod, errors::ConnectorError> { + Ok(services::CaptureSyncMethod::Individual) + } } #[async_trait::async_trait] @@ -624,15 +636,14 @@ impl .response .parse_struct("AdyenPaymentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - let is_manual_capture = - data.request.capture_method == Some(diesel_models::enums::CaptureMethod::Manual); types::RouterData::try_from(( types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }, - is_manual_capture, + data.request.capture_method, + false, )) .change_context(errors::ConnectorError::ResponseHandlingFailed) } @@ -1437,6 +1448,16 @@ impl api::IncomingWebhook for Adyen { ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let notif = get_webhook_object_from_body(request.body) .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + // for capture_event, original_reference field will have the authorized payment's PSP reference + if adyen::is_capture_event(&notif.event_code) { + return Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + notif + .original_reference + .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, + ), + )); + } if adyen::is_transaction_event(&notif.event_code) { return Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(notif.merchant_reference), diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index c4d0c4f2c50..7e85d8d42da 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -278,6 +278,7 @@ pub struct Response { refusal_reason: Option<String>, refusal_reason_code: Option<String>, additional_data: Option<AdditionalData>, + event_code: Option<WebhookEventCode>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -1449,7 +1450,8 @@ fn get_browser_info( fn get_additional_data(item: &types::PaymentsAuthorizeRouterData) -> Option<AdditionalData> { match item.request.capture_method { - Some(diesel_models::enums::CaptureMethod::Manual) => Some(AdditionalData { + Some(diesel_models::enums::CaptureMethod::Manual) + | Some(diesel_models::enums::CaptureMethod::ManualMultiple) => Some(AdditionalData { authorisation_type: Some(AuthType::PreAuth), manual_capture: Some(true), network_tx_reference: None, @@ -2822,6 +2824,7 @@ pub fn get_adyen_response( > { let status = storage_enums::AttemptStatus::foreign_from((is_capture_manual, response.result_code)); + let status = update_attempt_status_based_on_event_type_if_needed(status, &response.event_code); let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() { Some(types::ErrorResponse { code: response @@ -2860,6 +2863,42 @@ pub fn get_adyen_response( Ok((status, error, payments_response_data)) } +pub fn get_adyen_response_for_multiple_partial_capture( + response: Response, + status_code: u16, +) -> errors::CustomResult< + ( + storage_enums::AttemptStatus, + Option<types::ErrorResponse>, + types::PaymentsResponseData, + ), + errors::ConnectorError, +> { + let (status, error, _) = get_adyen_response(response.clone(), true, status_code)?; + let status = update_attempt_status_based_on_event_type_if_needed(status, &response.event_code); + let capture_sync_response_list = utils::construct_captures_response_hashmap(vec![response]); + Ok(( + status, + error, + types::PaymentsResponseData::MultipleCaptureResponse { + capture_sync_response_list, + }, + )) +} + +fn update_attempt_status_based_on_event_type_if_needed( + status: storage_enums::AttemptStatus, + event: &Option<WebhookEventCode>, +) -> storage_enums::AttemptStatus { + if status == storage_enums::AttemptStatus::Authorized + && event == &Some(WebhookEventCode::Capture) + { + storage_enums::AttemptStatus::Charged + } else { + status + } +} + pub fn get_redirection_response( response: RedirectionResponse, is_manual_capture: bool, @@ -3269,21 +3308,26 @@ pub fn get_present_to_shopper_metadata( impl<F, Req> TryFrom<( types::ResponseRouterData<F, AdyenPaymentResponse, Req, types::PaymentsResponseData>, + Option<storage_enums::CaptureMethod>, bool, )> for types::RouterData<F, Req, types::PaymentsResponseData> { type Error = Error; fn try_from( - items: ( + (item, capture_method, is_multiple_capture_psync_flow): ( types::ResponseRouterData<F, AdyenPaymentResponse, Req, types::PaymentsResponseData>, + Option<storage_enums::CaptureMethod>, bool, ), ) -> Result<Self, Self::Error> { - let item = items.0; - let is_manual_capture = items.1; + let is_manual_capture = utils::is_manual_capture(capture_method); let (status, error, payment_response_data) = match item.response { AdyenPaymentResponse::Response(response) => { - get_adyen_response(*response, is_manual_capture, item.http_code)? + if is_multiple_capture_psync_flow { + get_adyen_response_for_multiple_partial_capture(*response, item.http_code)? + } else { + get_adyen_response(*response, is_manual_capture, item.http_code)? + } } AdyenPaymentResponse::PresentToShopper(response) => { get_present_to_shopper_response(*response, is_manual_capture, item.http_code)? @@ -3319,9 +3363,15 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for AdyenCaptureRequest { type Error = Error; fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?; + let reference = match item.request.multiple_capture_data.clone() { + // if multiple capture request, send capture_id as our reference for the capture + Some(multiple_capture_request_data) => multiple_capture_request_data.capture_reference, + // if single capture request, send connector_request_reference_id(attempt_id) + None => item.connector_request_reference_id.clone(), + }; Ok(Self { merchant_account: auth_type.merchant_account, - reference: item.connector_request_reference_id.clone(), + reference, amount: Amount { currency: item.request.currency.to_string(), value: item.request.amount_to_capture, @@ -3348,13 +3398,18 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>> fn try_from( item: types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>, ) -> Result<Self, Self::Error> { + let connector_transaction_id = if item.data.request.multiple_capture_data.is_some() { + item.response.psp_reference + } else { + item.response.payment_psp_reference + }; Ok(Self { // From the docs, the only value returned is "received", outcome of refund is available // through refund notification webhook // For more info: https://docs.adyen.com/online-payments/capture status: storage_enums::AttemptStatus::Pending, response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.psp_reference), + resource_id: types::ResponseId::ConnectorTransactionId(connector_transaction_id), redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -3493,7 +3548,7 @@ pub struct AdyenAmountWH { pub currency: String, } -#[derive(Clone, Debug, Deserialize, strum::Display)] +#[derive(Clone, Debug, Deserialize, Serialize, strum::Display, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum WebhookEventCode { @@ -3507,6 +3562,8 @@ pub enum WebhookEventCode { SecondChargeback, PrearbitrationWon, PrearbitrationLost, + Capture, + CaptureFailed, #[serde(other)] Unknown, } @@ -3515,6 +3572,13 @@ pub fn is_transaction_event(event_code: &WebhookEventCode) -> bool { matches!(event_code, WebhookEventCode::Authorisation) } +pub fn is_capture_event(event_code: &WebhookEventCode) -> bool { + matches!( + event_code, + WebhookEventCode::Capture | WebhookEventCode::CaptureFailed + ) +} + pub fn is_refund_event(event_code: &WebhookEventCode) -> bool { matches!( event_code, @@ -3559,6 +3623,8 @@ impl ForeignFrom<(WebhookEventCode, Option<DisputeStatus>)> for webhooks::Incomi (WebhookEventCode::PrearbitrationWon, _) => Self::DisputeWon, (WebhookEventCode::PrearbitrationLost, _) => Self::DisputeLost, (WebhookEventCode::Unknown, _) => Self::EventNotSupported, + (WebhookEventCode::Capture, _) => Self::PaymentIntentSuccess, + (WebhookEventCode::CaptureFailed, _) => Self::PaymentIntentFailure, } } } @@ -3619,10 +3685,33 @@ impl From<AdyenNotificationRequestItemWH> for Response { refusal_reason: None, refusal_reason_code: None, additional_data: None, + event_code: Some(notif.event_code), } } } +impl utils::MultipleCaptureSyncResponse for Response { + fn get_connector_capture_id(&self) -> String { + self.psp_reference.clone() + } + + fn get_capture_attempt_status(&self) -> enums::AttemptStatus { + match self.result_code { + AdyenStatus::Authorised => enums::AttemptStatus::Charged, + _ => enums::AttemptStatus::CaptureFailed, + } + } + + fn is_capture_response(&self) -> bool { + self.event_code == Some(WebhookEventCode::Capture) + || self.event_code == Some(WebhookEventCode::CaptureFailed) + } + + fn get_connector_reference_id(&self) -> Option<String> { + Some(self.merchant_reference.clone()) + } +} + // Payouts #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs index 31696ee3868..de0470be2e4 100644 --- a/crates/router/src/connector/globalpay.rs +++ b/crates/router/src/connector/globalpay.rs @@ -483,11 +483,18 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .response .parse_struct("globalpay PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) + let is_multiple_capture_sync = match data.request.sync_type { + types::SyncRequestType::MultipleCaptureSync(_) => true, + types::SyncRequestType::SinglePaymentSync => false, + }; + types::RouterData::try_from(( + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }, + is_multiple_capture_sync, + )) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_multiple_capture_sync_method( diff --git a/crates/router/src/connector/globalpay/requests.rs b/crates/router/src/connector/globalpay/requests.rs index 4e3efcd12f2..ee62e8c2c2c 100644 --- a/crates/router/src/connector/globalpay/requests.rs +++ b/crates/router/src/connector/globalpay/requests.rs @@ -806,6 +806,7 @@ pub struct GlobalpayRefundRequest { pub struct GlobalpayCaptureRequest { pub amount: Option<String>, pub capture_sequence: Option<Sequence>, + pub reference: Option<String>, } #[derive(Default, Debug, Serialize)] diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index 6ef80213209..2100aa34f66 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -98,6 +98,11 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for requests::GlobalpayCaptureRe Sequence::Subsequent } }), + reference: value + .request + .multiple_capture_data + .as_ref() + .map(|mcd| mcd.capture_reference.clone()), }) } } @@ -228,7 +233,7 @@ fn get_payment_response( mandate_reference, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: response.reference, }), } } @@ -274,6 +279,35 @@ impl<F, T> } } +impl + TryFrom<( + types::PaymentsSyncResponseRouterData<GlobalpayPaymentsResponse>, + bool, + )> for types::PaymentsSyncRouterData +{ + type Error = Error; + + fn try_from( + (value, is_multiple_capture_sync): ( + types::PaymentsSyncResponseRouterData<GlobalpayPaymentsResponse>, + bool, + ), + ) -> Result<Self, Self::Error> { + if is_multiple_capture_sync { + let capture_sync_response_list = + utils::construct_captures_response_hashmap(vec![value.response]); + Ok(Self { + response: Ok(types::PaymentsResponseData::MultipleCaptureResponse { + capture_sync_response_list, + }), + ..value.data + }) + } else { + Self::try_from(value) + } + } +} + impl<F, T> TryFrom<types::ResponseRouterData<F, GlobalpayRefreshTokenResponse, T, types::AccessToken>> for types::RouterData<F, T, types::AccessToken> @@ -458,3 +492,21 @@ impl TryFrom<&api_models::payments::BankRedirectData> for PaymentMethodData { } } } + +impl utils::MultipleCaptureSyncResponse for GlobalpayPaymentsResponse { + fn get_connector_capture_id(&self) -> String { + self.id.clone() + } + + fn get_capture_attempt_status(&self) -> diesel_models::enums::AttemptStatus { + enums::AttemptStatus::from(self.status) + } + + fn is_capture_response(&self) -> bool { + true + } + + fn get_connector_reference_id(&self) -> Option<String> { + self.reference.clone() + } +} diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index d7f0cf6d404..04c9af069c7 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -21,10 +21,7 @@ use crate::{ consts, core::errors::{self, CustomResult}, pii::PeekInterface, - types::{ - self, api, storage::enums as storage_enums, transformers::ForeignTryFrom, - PaymentsCancelData, ResponseId, - }, + types::{self, api, transformers::ForeignTryFrom, PaymentsCancelData, ResponseId}, utils::{OptionExt, ValueExt}, }; @@ -1364,7 +1361,7 @@ mod error_code_error_message_tests { pub trait MultipleCaptureSyncResponse { fn get_connector_capture_id(&self) -> String; - fn get_capture_attempt_status(&self) -> storage_enums::AttemptStatus; + fn get_capture_attempt_status(&self) -> enums::AttemptStatus; fn is_capture_response(&self) -> bool; fn get_connector_reference_id(&self) -> Option<String> { None @@ -1397,6 +1394,11 @@ where hashmap } +pub fn is_manual_capture(capture_method: Option<enums::CaptureMethod>) -> bool { + capture_method == Some(enums::CaptureMethod::Manual) + || capture_method == Some(enums::CaptureMethod::ManualMultiple) +} + pub fn validate_currency( request_currency: types::storage::enums::Currency, merchant_config_currency: Option<types::storage::enums::Currency>, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 8e976740e6a..76d4198c88b 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1344,7 +1344,7 @@ where Ok(payment_data.to_owned()) } -#[derive(Clone)] +#[derive(Clone, PartialEq)] pub enum CallConnectorAction { Trigger, Avoid, @@ -1485,7 +1485,13 @@ pub fn should_call_connector<Op: Debug, F: Clone>( payment_data.payment_intent.status, storage_enums::IntentStatus::RequiresCapture | storage_enums::IntentStatus::PartiallyCaptured - ) + ) || (matches!( + payment_data.payment_intent.status, + storage_enums::IntentStatus::Processing + ) && matches!( + payment_data.payment_attempt.capture_method, + Some(storage_enums::CaptureMethod::ManualMultiple) + )) } "CompleteAuthorize" => true, "PaymentApprove" => true, diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index b6920387b13..1c01af79f56 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -157,10 +157,9 @@ impl types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsRespo types::PaymentsResponseData, >, ) -> RouterResult<Self> { - let mut capture_sync_response_list = HashMap::new(); - for connector_capture_id in pending_connector_capture_id_list { - self.request.connector_transaction_id = - types::ResponseId::ConnectorTransactionId(connector_capture_id.clone()); + let mut capture_sync_response_map = HashMap::new(); + if let payments::CallConnectorAction::HandleResponse(_) = call_connector_action { + // webhook consume flow, only call connector once. Since there will only be a single event in every webhook let resp = services::execute_connector_processing_step( state, connector_integration.clone(), @@ -170,30 +169,40 @@ impl types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsRespo ) .await .to_payment_failed_response()?; - let capture_sync_response = match resp.response { - Err(err) => types::CaptureSyncResponse::Error { - code: err.code, - message: err.message, - reason: err.reason, - status_code: err.status_code, - }, - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id, - connector_response_reference_id, - .. - }) => types::CaptureSyncResponse::Success { - resource_id, - status: resp.status, - connector_response_reference_id, - }, - // this error is never meant to occur. response type will always be PaymentsResponseData::TransactionResponse - _ => Err(ApiErrorResponse::PreconditionFailed { message: "Response type must be PaymentsResponseData::TransactionResponse for payment sync".into() })?, - }; - capture_sync_response_list.insert(connector_capture_id.clone(), capture_sync_response); + Ok(resp) + } else { + // in trigger, call connector for every capture_id + for connector_capture_id in pending_connector_capture_id_list { + self.request.connector_transaction_id = + types::ResponseId::ConnectorTransactionId(connector_capture_id.clone()); + let resp = services::execute_connector_processing_step( + state, + connector_integration.clone(), + &self, + call_connector_action.clone(), + None, + ) + .await + .to_payment_failed_response()?; + match resp.response { + Err(err) => { + capture_sync_response_map.insert(connector_capture_id, types::CaptureSyncResponse::Error { + code: err.code, + message: err.message, + reason: err.reason, + status_code: err.status_code, + }); + }, + Ok(types::PaymentsResponseData::MultipleCaptureResponse { capture_sync_response_list })=> { + capture_sync_response_map.extend(capture_sync_response_list.into_iter()); + } + _ => Err(ApiErrorResponse::PreconditionFailed { message: "Response type must be PaymentsResponseData::MultipleCaptureResponse for payment sync".into() })?, + }; + } + self.response = Ok(types::PaymentsResponseData::MultipleCaptureResponse { + capture_sync_response_list: capture_sync_response_map, + }); + Ok(self) } - self.response = Ok(types::PaymentsResponseData::MultipleCaptureResponse { - capture_sync_response_list, - }); - Ok(self) } } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index d29cfbf100c..7ae71ec2a6b 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1448,16 +1448,30 @@ pub(crate) fn validate_capture_method( } #[instrument(skip_all)] -pub(crate) fn validate_status(status: storage_enums::IntentStatus) -> RouterResult<()> { +pub(crate) fn validate_status_with_capture_method( + status: storage_enums::IntentStatus, + capture_method: storage_enums::CaptureMethod, +) -> RouterResult<()> { + if status == storage_enums::IntentStatus::Processing + && !(capture_method == storage_enums::CaptureMethod::ManualMultiple) + { + return Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { + field_name: "capture_method".to_string(), + current_flow: "captured".to_string(), + current_value: capture_method.to_string(), + states: "manual_multiple".to_string() + })); + } utils::when( status != storage_enums::IntentStatus::RequiresCapture - && status != storage_enums::IntentStatus::PartiallyCaptured, + && status != storage_enums::IntentStatus::PartiallyCaptured + && status != storage_enums::IntentStatus::Processing, || { Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { field_name: "payment.status".to_string(), current_flow: "captured".to_string(), current_value: status.to_string(), - states: "requires_capture, partially captured".to_string() + states: "requires_capture, partially_captured, processing".to_string() })) }, ) diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 596e25f0528..054f9a31b90 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -61,10 +61,6 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - helpers::validate_status(payment_intent.status)?; - - helpers::validate_amount_to_capture(payment_intent.amount, request.amount_to_capture)?; - payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( payment_intent.payment_id.as_str(), @@ -83,6 +79,10 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu .capture_method .get_required_value("capture_method")?; + helpers::validate_status_with_capture_method(payment_intent.status, capture_method)?; + + helpers::validate_amount_to_capture(payment_intent.amount, request.amount_to_capture)?; + helpers::validate_capture_method(capture_method)?; let (multiple_capture_data, connector_response) = if capture_method
2023-09-07T11:34: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 --> This PR enables multiple partial capture for Adyen. ### 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)? --> Manual ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
05696d326f87a08919f177e67bfa54e09fba5147
juspay/hyperswitch
juspay__hyperswitch-2326
Bug: [FEATURE]: [Coinbase] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs index acc08e36e49..6cc097bc9d8 100644 --- a/crates/router/src/connector/coinbase/transformers.rs +++ b/crates/router/src/connector/coinbase/transformers.rs @@ -136,7 +136,7 @@ impl<F, T> .last() .ok_or(errors::ConnectorError::ResponseHandlingFailed)? .clone(); - let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id); + let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id.clone()); let attempt_status = timeline.status.clone(); let response_data = timeline.context.map_or( Ok(types::PaymentsResponseData::TransactionResponse { @@ -145,7 +145,7 @@ impl<F, T> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.data.id.clone()), }), |context| { Ok(types::PaymentsResponseData::TransactionUnresolvedResponse{ @@ -155,7 +155,7 @@ impl<F, T> message: "Please check the transaction in coinbase dashboard and resolve manually" .to_string(), }), - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.data.id), }) }, );
2023-10-05T17:50:31Z
## 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 --> Relevant documentation [here](https://docs.cloud.coinbase.com/commerce/docs/webhooks-events). I'm not 100% sure what `code` is in the documentation but they haven't provided more clarity, the only other identifier for the transaction is id, so I've used that. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #2326 ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
bb2ba0815330578295de8036ea1a5e6d66a36277
juspay/hyperswitch
juspay__hyperswitch-2334
Bug: [FEATURE]: [Klarna] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index 31e356d4765..563410ee99d 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -159,12 +159,14 @@ impl TryFrom<types::PaymentsResponseRouterData<KlarnaPaymentsResponse>> ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id), + resource_id: types::ResponseId::ConnectorTransactionId( + item.response.order_id.clone(), + ), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.order_id.clone()), }), status: item.response.fraud_status.into(), ..item.data
2023-10-17T13:15:34Z
## 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 --> ### 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). --> Resolves #2334 ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
67d006272158372a4b9ec65cbbe7b2ae8f35eb69
juspay/hyperswitch
juspay__hyperswitch-2325
Bug: [FEATURE]: [Bitpay] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs index 5af20d6423f..89dd2368b2b 100644 --- a/crates/router/src/connector/bitpay/transformers.rs +++ b/crates/router/src/connector/bitpay/transformers.rs @@ -134,6 +134,7 @@ pub struct BitpayPaymentResponseData { pub expiration_time: Option<i64>, pub current_time: Option<i64>, pub id: String, + pub order_id: Option<String>, pub low_fee_detected: Option<bool>, pub display_amount_paid: Option<String>, pub exception_status: ExceptionStatus, @@ -162,7 +163,7 @@ impl<F, T> .data .url .map(|x| services::RedirectForm::from((x, services::Method::Get))); - let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id); + let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id.clone()); let attempt_status = item.response.data.status; Ok(Self { status: enums::AttemptStatus::from(attempt_status), @@ -172,7 +173,11 @@ impl<F, T> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: item + .response + .data + .order_id + .or(Some(item.response.data.id)), }), ..item.data })
2023-10-15T04:51:11Z
## 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 --> [Relevant documentation](https://developer.bitpay.com/docs/create-invoice#notificationurl) ### 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 #2325 ## 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)? --> Make any Payment for connector Bitpay and see that you are getting "reference_id" field in the payments response of hyperswitch. It should not be 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
4563935372d2cdff3f746fa86a47f1166ffd32ac
juspay/hyperswitch
juspay__hyperswitch-2324
Bug: [FEATURE]: [Bambora] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index bfcd9846292..e686186c901 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -214,7 +214,7 @@ impl<F, T> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(pg_response.order_number.to_string()), }), ..item.data }), @@ -238,7 +238,9 @@ impl<F, T> .change_context(errors::ConnectorError::ResponseHandlingFailed)?, ), network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some( + item.data.connector_request_reference_id.to_string(), + ), }), ..item.data })
2023-10-18T17:09:58Z
## Type of Change - [x] New feature ## Description The `connector_response_reference_id` parameter has been set for the Bambora Payment Solutions for uniform reference and transaction tracking. ### File Changes - [x] This PR modifies the Bambora Transformers file. **Location- router/src/connector/bambora/transformers.rs** ## Motivation and Context This PR was raised so that it Fixes #2324 ! ## How did you test it? - **I ran the following command, and all the errors were addressed properly, and the build was successful.** ```bash cargo clippy --all-features ``` ![build](https://github.com/juspay/hyperswitch/assets/47860497/74082946-5ce8-4202-87f2-05648e7fd2ff) - The code changes were formatted with the following command to fix styling issues. ```bash cargo +nightly fmt ``` ## 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
03b6eaebeccd628115b8f4c52aa8645abbccdd29
juspay/hyperswitch
juspay__hyperswitch-2323
Bug: [FEATURE]: [Authorizedotnet] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index a2faeddb50f..1b7480f78e4 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -540,7 +540,9 @@ impl<F, T> mandate_reference: None, connector_metadata: metadata, network_txn_id: transaction_response.network_trans_id.clone(), - connector_response_reference_id: None, + connector_response_reference_id: Some( + transaction_response.transaction_id.clone(), + ), }), }, ..item.data @@ -604,7 +606,9 @@ impl<F, T> mandate_reference: None, connector_metadata: metadata, network_txn_id: transaction_response.network_trans_id.clone(), - connector_response_reference_id: None, + connector_response_reference_id: Some( + transaction_response.transaction_id.clone(), + ), }), }, ..item.data @@ -887,13 +891,13 @@ impl<F, Req> Ok(Self { response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( - transaction.transaction_id, + transaction.transaction_id.clone(), ), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(transaction.transaction_id.clone()), }), status: payment_status, ..item.data
2023-10-08T15:12: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 --> Implement `connector_response_reference_id` as reference for Authorizedotnet ### 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). --> Resolves #2323 ## 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)? --> Manually ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3f1e7c2152a839a6fe69f60b906277ca831e7611
juspay/hyperswitch
juspay__hyperswitch-2322
Bug: [FEATURE]: [Airwallex] Use `connector_response_reference_id` as reference to merchant ### :memo: Feature Description - Reference id are used to map transactions in the connector’s dashboard. - Hyperswitch manages several reference ids, such as `payment_id`, `attempt_id`, and `connector_transaction_id` for a single transaction. - However, merchants may encounter uncertainty when determining which ID to utilize in the connector dashboard to identify the payment. ### :hammer: Possible Implementation - When we receive a response from the connector for the payment, we deserialize it and populate the `response` field in RouterData. - For the `TransactionResponse` type, we must fill the `connector_response_reference_id` with a corresponding reference id for the merchant to identify the transaction. - One might need to have exposure to api docs of the connector for which it is being implemented to decide what to fill in connector_response_reference_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1735 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index e38999d495b..d3824e9d0da 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -569,12 +569,12 @@ impl<F, T> status, reference_id: Some(item.response.id.clone()), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, charge_id: None, }), @@ -612,12 +612,12 @@ impl status, reference_id: Some(item.response.id.clone()), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, charge_id: None, }),
2023-10-31T14:25:53Z
## Type of Change - [x] New feature ## Description The `connector_response_reference_id` parameter has been set for the Airwallex Payment Solutions for uniform reference and transaction tracking. ### File Changes - [x] This PR modifies the Airwallex Transformers file. **Location- router/src/connector/airwallex/transformers.rs** ## Motivation and Context This PR was raised so that it Fixes #2322 ! ## How did you test it? - **I ran the following command, and all the errors were addressed properly, and the build was successful.** ```bash cargo clippy --all-features ``` ![build](https://github.com/juspay/hyperswitch/assets/47860497/69cb247b-0a67-43c6-b006-5ec0c012822f) - The code changes were formatted with the following command to fix styling issues. ```bash cargo +nightly fmt ``` ## 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
2798f575605cc4439166344e57ff19b612f1304a
juspay/hyperswitch
juspay__hyperswitch-2319
Bug: [FEATURE]: [Tsys] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs index d8516c8293b..83134568c05 100644 --- a/crates/router/src/connector/tsys/transformers.rs +++ b/crates/router/src/connector/tsys/transformers.rs @@ -34,6 +34,7 @@ pub struct TsysPaymentAuthSaleRequest { cardholder_authentication_method: String, #[serde(rename = "developerID")] developer_id: Secret<String>, + order_number: String, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest { @@ -57,6 +58,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest { terminal_operating_environment: "ON_MERCHANT_PREMISES_ATTENDED".to_string(), cardholder_authentication_method: "NOT_AUTHENTICATED".to_string(), developer_id: connector_auth.developer_id, + order_number: item.connector_request_reference_id.clone(), }; if item.request.is_auto_capture()? { Ok(Self::Sale(auth_data))
2023-10-18T13:20:35Z
## Type of Change - [x] New feature ## Description The `connector_request_reference_id` parameter has been set for the Tsys Payment Solutions for uniform reference and transaction tracking. ### File Changes - [x] This PR modifies the Tsys Transformers file. **Location- router/src/connector/tsys/transformers.rs** ## Motivation and Context This PR was raised so that it Fixes #2319 ! ## How did you test it? - **I ran the following command, and all the errors were addressed properly, and the build was successful.** ```bash cargo clippy --all-features ``` ![build](https://github.com/juspay/hyperswitch/assets/47860497/6ad99801-288c-4bd5-b125-ddf19c645f1a) - The code changes were formatted with the following command to fix styling issues. ```bash cargo +nightly fmt ``` ## 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
6cf8f0582cfa4f6a58c67a868cb67846970b3835
juspay/hyperswitch
juspay__hyperswitch-2321
Bug: [FEATURE]: [Worldpay] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index aabe27fc4eb..61d04a8e9f1 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -167,10 +167,14 @@ impl debt_repayment: None, }, merchant: Merchant { - entity: item.router_data.attempt_id.clone().replace('_', "-"), + entity: item + .router_data + .connector_request_reference_id + .clone() + .replace('_', "-"), ..Default::default() }, - transaction_reference: item.router_data.attempt_id.clone(), + transaction_reference: item.router_data.connector_request_reference_id.clone(), channel: None, customer: None, })
2023-10-11T18:13:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> As mentioned in the issue #2321 , I had to work on the attempt_id and payment_id in the Router data , it should have been replaced with the new introduced connector_request_reference_id. I think I have did it. please have a look and merge if it's done @VedantKhairnar @srujanchikke ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cd9030506c6843c0331bc93d67590d12e280ecca
juspay/hyperswitch
juspay__hyperswitch-2320
Bug: [FEATURE]: [Worldline] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index f1267c09766..d02ab60c8b9 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -40,11 +40,18 @@ pub struct AmountOfMoney { pub currency_code: String, } +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct References { + pub merchant_reference: String, +} + #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Order { pub amount_of_money: AmountOfMoney, pub customer: Customer, + pub references: References, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] @@ -202,6 +209,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest { currency_code: item.request.currency.to_string().to_uppercase(), }, customer, + references: References { + merchant_reference: item.connector_request_reference_id.clone(), + }, }; let shipping = item
2023-10-08T15:33:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Replace `payment_id` with `connector_request_reference_id` in worldline. Closes #2320 ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
53d760460305e16f03d86f699acb035151dfdfad
juspay/hyperswitch
juspay__hyperswitch-2317
Bug: [FEATURE]: [Stax] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 42c7c02a363..4ee28be1937 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -23,6 +23,7 @@ pub struct StaxPaymentsRequest { is_refundable: bool, pre_auth: bool, meta: StaxPaymentsRequestMetaData, + idempotency_id: Option<String>, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { @@ -51,6 +52,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { Err(errors::ConnectorError::InvalidWalletToken)? } }), + idempotency_id: Some(item.connector_request_reference_id.clone()), }) } api::PaymentMethodData::BankDebit( @@ -69,6 +71,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { Err(errors::ConnectorError::InvalidWalletToken)? } }), + idempotency_id: Some(item.connector_request_reference_id.clone()), }) } api::PaymentMethodData::BankDebit(_) @@ -282,6 +285,7 @@ pub struct StaxPaymentsResponse { child_captures: Vec<StaxChildCapture>, #[serde(rename = "type")] payment_response_type: StaxPaymentResponseTypes, + idempotency_id: Option<String>, } #[derive(Debug, Deserialize, Serialize)] @@ -323,12 +327,14 @@ impl<F, T> Ok(Self { status, response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some( + item.response.idempotency_id.unwrap_or(item.response.id), + ), }), ..item.data })
2023-10-02T10:52:24Z
## 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 fixes #2348 issue in STAX and uses connector_response_reference_id as reference to merchant. ### 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). --> Fixes #2348 and fixes #2317. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
36805411772da00719a716d05c650f10ca990d49
juspay/hyperswitch
juspay__hyperswitch-2316
Bug: [FEATURE]: [Shift4] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 23c91e48d8c..0dd3b858349 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -717,6 +717,7 @@ impl<T, F> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { + let connector_id = types::ResponseId::ConnectorTransactionId(item.response.id.clone()); Ok(Self { status: enums::AttemptStatus::foreign_from(( item.response.captured, @@ -727,7 +728,7 @@ impl<T, F> item.response.status, )), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + resource_id: connector_id, redirection_data: item .response .flow @@ -737,7 +738,7 @@ impl<T, F> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.id), }), ..item.data })
2023-10-08T00:13:23Z
## 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 --> fixes #2316 ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
31431e41357d4d3d12668fa0d678cce0b3d86611
juspay/hyperswitch
juspay__hyperswitch-2315
Bug: [FEATURE]: [Rapyd] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 044a64b413c..939004f8ea9 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -37,6 +37,7 @@ pub struct RapydPaymentsRequest { pub currency: enums::Currency, pub payment_method: PaymentMethod, pub payment_method_options: Option<PaymentMethodOptions>, + pub merchant_reference_id: Option<String>, pub capture: Option<bool>, pub description: Option<String>, pub complete_payment_url: Option<String>, @@ -162,6 +163,7 @@ impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPay payment_method, capture, payment_method_options, + merchant_reference_id: Some(item.router_data.connector_request_reference_id.clone()), description: None, error_payment_url: Some(return_url.clone()), complete_payment_url: Some(return_url),
2024-10-12T13:47:08Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add connector_request_reference_id support for Rapyd - Used `merchant_reference_id` as the reference id, while implementing this! Resolves #2315 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9597215a66e38b0021bd804ffe4d9d040e30f8f9
juspay/hyperswitch
juspay__hyperswitch-2314
Bug: [FEATURE]: [PowerTranz] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index 4703a81f30f..4032f8019b0 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -123,7 +123,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest .to_string(), three_d_secure, source, - order_identifier: item.payment_id.clone(), + order_identifier: item.connector_request_reference_id.clone(), // billing_address, // shipping_address, extended_data, @@ -239,6 +239,7 @@ pub struct PowertranzBaseResponse { iso_response_code: String, redirect_data: Option<String>, response_message: String, + order_identifier: String, } impl ForeignFrom<(u8, bool, bool)> for enums::AttemptStatus { @@ -297,7 +298,7 @@ impl<F, T> let connector_transaction_id = item .response .original_trxn_identifier - .unwrap_or(item.response.transaction_identifier); + .unwrap_or(item.response.transaction_identifier.clone()); let redirection_data = item.response .redirect_data @@ -311,7 +312,7 @@ impl<F, T> mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(item.response.order_identifier), }), Err, );
2023-10-02T08:23:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### 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). --> Fixes #2345 ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
89cb63be3328010d26b5f6322449fc50e80593e4
juspay/hyperswitch
juspay__hyperswitch-2313
Bug: [FEATURE]: [PayU] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs index 7b3792c0e24..dc65d6e1d76 100644 --- a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs @@ -34,6 +34,7 @@ pub struct PayuPaymentsRequest { description: String, pay_methods: PayuPaymentMethod, continue_url: Option<String>, + ext_order_id: Option<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -133,6 +134,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest { .to_string(), ), merchant_pos_id: auth_type.merchant_pos_id, + ext_order_id: Some(item.connector_request_reference_id.clone()), total_amount: item.request.amount, currency_code: item.request.currency, description: item.description.clone().ok_or(
2024-10-18T03:14:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add connector_request_reference_id support for PayU - Used `extOrderId` as the reference id based on the [PayU documentation](https://developers.payu.com/europe/api/#tag/Order/operation/create-an-order) reference: ![image](https://github.com/user-attachments/assets/f730028d-1fa4-4222-b2ad-7e2b4caeed9e) Resolves #2313 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
c3b0f7c1d6ad95034535048aa50ff6abe9ed6aa0
juspay/hyperswitch
juspay__hyperswitch-2312
Bug: [FEATURE]: [Payeezy] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index d6c22ba67c3..98e8ea12c00 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -67,6 +67,7 @@ pub struct PayeezyPaymentsRequest { pub currency_code: String, pub credit_card: PayeezyPaymentMethod, pub stored_credentials: Option<StoredCredentials>, + pub reference: String, } #[derive(Serialize, Debug)] @@ -118,6 +119,7 @@ fn get_card_specific_payment_data( currency_code, credit_card, stored_credentials, + reference: item.connector_request_reference_id.clone(), }) } fn get_transaction_type_and_stored_creds( @@ -252,6 +254,7 @@ pub struct PayeezyPaymentsResponse { pub gateway_resp_code: String, pub gateway_message: String, pub stored_credentials: Option<PaymentsStoredCredentials>, + pub reference: Option<String>, } #[derive(Debug, Deserialize)] @@ -354,13 +357,17 @@ impl<F, T> status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transaction_id, + item.response.transaction_id.clone(), ), redirection_data: None, mandate_reference, connector_metadata: metadata, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some( + item.response + .reference + .unwrap_or(item.response.transaction_id), + ), }), ..item.data })
2023-10-01T19:11: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 --> Add `connector_response_reference_id` support for Payeezy - Used `transaction_id` as the reference id, while implementing this! Resolves #2343 and resolves #2312. ### 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? Need help testing! <!-- 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
89cb63be3328010d26b5f6322449fc50e80593e4
juspay/hyperswitch
juspay__hyperswitch-2311
Bug: [FEATURE]: [OpenNode] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs index aa3fae3a516..b367012ca75 100644 --- a/crates/router/src/connector/opennode/transformers.rs +++ b/crates/router/src/connector/opennode/transformers.rs @@ -19,6 +19,7 @@ pub struct OpennodePaymentsRequest { auto_settle: bool, success_url: String, callback_url: String, + order_id: String, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpennodePaymentsRequest { @@ -237,6 +238,7 @@ fn get_crypto_specific_payment_data( auto_settle, success_url, callback_url, + order_id: item.connector_request_reference_id.clone(), }) }
2023-10-15T19:43:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Use connector_request_reference_id as reference to the connector #2311 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables Following are the paths where you can find config files: 1. hyperswitch/crates/router/src/connector/opennode/transformers.rs ## Motivation and Context To solve inconsistency in RouterData and it solves the Issue #2311 ## How did you test it? Need help in doing test? ## Checklist - [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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
027385eca6e76c5cbe65450f058ececa012d1175
juspay/hyperswitch
juspay__hyperswitch-2309
Bug: [FEATURE]: [Nuvei] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index cf7d480e0c1..2fd1a9c272f 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -384,7 +384,7 @@ impl TryFrom<&types::PaymentsAuthorizeSessionTokenRouterData> for NuveiSessionRe let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?; let merchant_id = connector_meta.merchant_id; let merchant_site_id = connector_meta.merchant_site_id; - let client_request_id = item.attempt_id.clone(); + let client_request_id = item.connector_request_reference_id.clone(); let time_stamp = date_time::DateTime::<date_time::YYYYMMDDHHmmss>::from(date_time::now()); let merchant_secret = connector_meta.merchant_secret; Ok(Self { @@ -737,7 +737,7 @@ impl<F> amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, currency: item.request.currency, connector_auth_type: item.connector_auth_type.clone(), - client_request_id: item.attempt_id.clone(), + client_request_id: item.connector_request_reference_id.clone(), session_token: data.1, capture_method: item.request.capture_method, ..Default::default() @@ -914,7 +914,7 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, String)> for NuveiPay amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, currency: item.request.currency, connector_auth_type: item.connector_auth_type.clone(), - client_request_id: item.attempt_id.clone(), + client_request_id: item.connector_request_reference_id.clone(), session_token: data.1, capture_method: item.request.capture_method, ..Default::default() @@ -1018,7 +1018,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for NuveiPaymentFlowRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { Self::try_from(NuveiPaymentRequestData { - client_request_id: item.attempt_id.clone(), + client_request_id: item.connector_request_reference_id.clone(), connector_auth_type: item.connector_auth_type.clone(), amount: utils::to_currency_base_unit( item.request.amount_to_capture, @@ -1034,7 +1034,7 @@ impl TryFrom<&types::RefundExecuteRouterData> for NuveiPaymentFlowRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundExecuteRouterData) -> Result<Self, Self::Error> { Self::try_from(NuveiPaymentRequestData { - client_request_id: item.attempt_id.clone(), + client_request_id: item.connector_request_reference_id.clone(), connector_auth_type: item.connector_auth_type.clone(), amount: utils::to_currency_base_unit( item.request.refund_amount, @@ -1061,7 +1061,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NuveiPaymentFlowRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { Self::try_from(NuveiPaymentRequestData { - client_request_id: item.attempt_id.clone(), + client_request_id: item.connector_request_reference_id.clone(), connector_auth_type: item.connector_auth_type.clone(), amount: utils::to_currency_base_unit( item.request.get_amount()?,
2023-10-08T01:05:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> `connector_request_reference_id` is being passed as "attempt_id" or "payment_id" to improve consistency in transmitting payment information to the Nuvei payment gateway. ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
3f1e7c2152a839a6fe69f60b906277ca831e7611
juspay/hyperswitch
juspay__hyperswitch-2307
Bug: [FEATURE]: [Nexi Nets] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 7b2a41cfb0b..897d8f639d3 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -27,6 +27,7 @@ pub struct NexinetsPaymentsRequest { payment: Option<NexinetsPaymentDetails>, #[serde(rename = "async")] nexinets_async: NexinetsAsyncDetails, + merchant_order_id: Option<String>, } #[derive(Debug, Serialize, Default)] @@ -172,6 +173,11 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest { failure_url: return_url, }; let (payment, product) = get_payment_details_and_product(item)?; + let merchant_order_id = match item.payment_method { + // Merchant order id is sent only in case of card payment + enums::PaymentMethod::Card => Some(item.connector_request_reference_id.clone()), + _ => None, + }; Ok(Self { initial_amount: item.request.amount, currency: item.request.currency, @@ -179,6 +185,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest { product, payment, nexinets_async, + merchant_order_id, }) } }
2023-10-09T20:55:20Z
## Type of Change - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description For all payment methods, Hyperswitch should transmit a reference to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. In this PR, such reference is obtained by calling `connector_request_reference_id()` in `RouterData`. The result is then passed as the "merchantOrderId" parameter to the NexiNets API, as per the [official documentation](https://developer.nexigroup.com/payengine/en-EU/api/payengine-api-v1/#orders-post-body-merchantorderid). ### 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 #2307 ## How did you test it? ## Checklist - [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 - [x] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8029a895b2c27a1ac14a19aea23bbc06cc364809
juspay/hyperswitch
juspay__hyperswitch-2308
Bug: [FEATURE]: [Noon] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 6c3084a75e4..3e584e204ae 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -264,7 +264,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { currency, channel: NoonChannels::Web, category, - reference: item.payment_id.clone(), + reference: item.connector_request_reference_id.clone(), name, }; let payment_action = if item.request.is_auto_capture()? {
2023-10-05T17:35:30Z
## 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 --> Closes #2308 Use `connector_request_reference_id` instead of `payment_id` as Order reference ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
414996592b3016bfa9f3399319c6e02ccd333c68
juspay/hyperswitch
juspay__hyperswitch-2306
Bug: [FEATURE]: [NMI] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 3f64ff9eaca..582bb9f7367 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -49,6 +49,7 @@ pub struct NmiPaymentsRequest { currency: enums::Currency, #[serde(flatten)] payment_method: PaymentMethod, + orderid: String, } #[derive(Debug, Serialize)] @@ -94,6 +95,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NmiPaymentsRequest { amount, currency: item.request.currency, payment_method, + orderid: item.connector_request_reference_id.clone(), }) } } @@ -206,6 +208,7 @@ impl TryFrom<&types::SetupMandateRouterData> for NmiPaymentsRequest { amount: 0.0, currency: item.request.currency, payment_method, + orderid: item.connector_request_reference_id.clone(), }) } }
2023-10-30T02:40:45Z
Add orderid with value of connector_request_reference_id in NMI transformers. Fixes #2306 ## 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 --> ### 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)? --> Make any Payment for connector NMI and see that you are getting "reference_id" field in the logs of payment request. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8125ea19912f6d6446412d13842e35545cc1a484
juspay/hyperswitch
juspay__hyperswitch-2305
Bug: [FEATURE]: [Multisafepay] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/multisafepay.rs b/crates/router/src/connector/multisafepay.rs index 1629f2ab36d..120ea23d7ca 100644 --- a/crates/router/src/connector/multisafepay.rs +++ b/crates/router/src/connector/multisafepay.rs @@ -165,7 +165,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe .change_context(errors::ConnectorError::FailedToObtainAuthType)? .api_key .expose(); - let ord_id = req.payment_id.clone(); + let ord_id = req.connector_request_reference_id.clone(); Ok(format!("{url}v1/json/orders/{ord_id}?api_key={api_key}")) } @@ -341,7 +341,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .change_context(errors::ConnectorError::FailedToObtainAuthType)? .api_key .expose(); - let ord_id = req.payment_id.clone(); + let ord_id = req.connector_request_reference_id.clone(); Ok(format!( "{url}v1/json/orders/{ord_id}/refunds?api_key={api_key}" )) @@ -428,7 +428,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .change_context(errors::ConnectorError::FailedToObtainAuthType)? .api_key .expose(); - let ord_id = req.payment_id.clone(); + let ord_id = req.connector_request_reference_id.clone(); Ok(format!( "{url}v1/json/orders/{ord_id}/refunds?api_key={api_key}" )) diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index dfc7bad277d..a8366fadf81 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -380,7 +380,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques Ok(Self { payment_type, gateway, - order_id: item.payment_id.to_string(), + order_id: item.connector_request_reference_id.to_string(), currency: item.request.currency.to_string(), amount: item.request.amount, description,
2023-10-09T07:12:04Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Addressing Issue [#2305](https://github.com/juspay/hyperswitch/issues/2305): Use connector_request_reference_id as reference to the connector - Modified two files in `hyperswitch/crates/router/src/connector/` - `multisafepay.rs` - `multisafepay/transformers.rs` - Rebase with changes from commit [12b5341](https://github.com/juspay/hyperswitch/commit/12b534197276ccc4aa9575e6b518bcc50b597bee) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
e02838eb5d3da97ef573926ded4a318ed24b6f1c
juspay/hyperswitch
juspay__hyperswitch-2303
Bug: [FEATURE]: [Klarna] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index b31d56d51b9..31e356d4765 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -45,6 +45,7 @@ pub struct KlarnaPaymentsRequest { order_amount: i64, purchase_country: String, purchase_currency: enums::Currency, + merchant_reference1: String, } #[derive(Default, Debug, Deserialize)] @@ -140,6 +141,7 @@ impl TryFrom<&KlarnaRouterData<&types::PaymentsAuthorizeRouterData>> for KlarnaP total_amount: i64::from(data.quantity) * (data.amount), }) .collect(), + merchant_reference1: item.router_data.connector_request_reference_id.clone(), }), None => Err(report!(errors::ConnectorError::MissingRequiredField { field_name: "product_name"
2023-10-08T05:56:23Z
## 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 --> Included a `merchant_reference1` field in `KlarnaPaymentsRequest` and map it to `connector_request_reference_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)? --> ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
b5feab61d950921c75267ad88e944e7e2c4af3ca
juspay/hyperswitch
juspay__hyperswitch-2302
Bug: [FEATURE]: [Iatapay] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index f98798fe5be..d4731b024c8 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -110,7 +110,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest { utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?; let payload = Self { merchant_id: IatapayAuthType::try_from(&item.connector_auth_type)?.merchant_id, - merchant_payment_id: Some(item.payment_id.clone()), + merchant_payment_id: Some(item.connector_request_reference_id.clone()), amount, currency: item.request.currency.to_string(), country: country.clone(),
2023-10-25T18:56:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> fixes #2302 ### 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)? --> Make any Payment for connector Iatapay and see that you are getting "reference_id" field in the logs of payment request. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
2815443c1b147e005a2384ff817292b1845a9f88
juspay/hyperswitch
juspay__hyperswitch-2300
Bug: [FEATURE]: [GlobalPayments] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index 7a35a5f578f..78a83e70026 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -39,7 +39,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobalpayPaymentsRequest { account_name, amount: Some(item.request.amount.to_string()), currency: item.request.currency.to_string(), - reference: item.attempt_id.to_string(), + reference: item.connector_request_reference_id.to_string(), country: item.get_billing_country()?, capture_mode: Some(requests::CaptureMode::from(item.request.capture_method)), payment_method: requests::PaymentMethod {
2023-10-10T05:28:11Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cf0db35923d39caca9bf267b7d87a3f215884b66
juspay/hyperswitch
juspay__hyperswitch-2298
Bug: [FEATURE]: [Fiserv] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index c9c2f0c4087..ae8eed0af31 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -62,6 +62,7 @@ pub struct Amount { pub struct TransactionDetails { capture_flag: Option<bool>, reversal_reason_code: Option<String>, + merchant_transaction_id: String, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] @@ -112,6 +113,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FiservPaymentsRequest { Some(enums::CaptureMethod::Automatic) | None )), reversal_reason_code: None, + merchant_transaction_id: item.connector_request_reference_id.clone(), }; let metadata = item.get_connector_meta()?; let session: SessionObject = metadata @@ -208,6 +210,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for FiservCancelRequest { transaction_details: TransactionDetails { capture_flag: None, reversal_reason_code: Some(item.request.get_cancellation_reason()?), + merchant_transaction_id: item.connector_request_reference_id.clone(), }, }) } @@ -407,6 +410,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for FiservCaptureRequest { transaction_details: TransactionDetails { capture_flag: Some(true), reversal_reason_code: None, + merchant_transaction_id: item.connector_request_reference_id.clone(), }, merchant_details: MerchantDetails { merchant_id: auth.merchant_account,
2023-10-26T11:51:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Make any Payment for connector Fiserv and see that you are getting "reference_id" field in the logs of payment request. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
6dc71fe9923a793b76eee2ea1ac1060ab584a303
juspay/hyperswitch
juspay__hyperswitch-2297
Bug: [FEATURE]: [Dlocal] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 5146dd0ea03..668a335cce8 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -145,7 +145,7 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP .clone() .map(|_| "1".to_string()), }), - order_id: item.router_data.payment_id.clone(), + order_id: item.router_data.connector_request_reference_id.clone(), three_dsecure: match item.router_data.auth_type { diesel_models::enums::AuthenticationType::ThreeDs => { Some(ThreeDSecureReqData { force: true }) @@ -237,7 +237,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for DlocalPaymentsCaptureRequest authorization_id: item.request.connector_transaction_id.clone(), amount: item.request.amount_to_capture, currency: item.request.currency.to_string(), - order_id: item.payment_id.clone(), + order_id: item.connector_request_reference_id.clone(), }) } }
2023-10-26T19:01:06Z
…cal connector #2297 ## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Use connector_request_reference_id as reference to the connector #2297 ### 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. hyperswitch/crates/router/src/connector/Dlocal/transformers.rs ## Motivation and Context To solve inconsistency in RouterData and it solves the Issue #2297 ## How did you test it? Make any Payment for connector Dlocal and see that you are getting "reference_id" field in the logs of payment request. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
6dc71fe9923a793b76eee2ea1ac1060ab584a303
juspay/hyperswitch
juspay__hyperswitch-2294
Bug: [FEATURE]: [Bitpay] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs index c5c20608a75..5af20d6423f 100644 --- a/crates/router/src/connector/bitpay/transformers.rs +++ b/crates/router/src/connector/bitpay/transformers.rs @@ -60,6 +60,7 @@ pub struct BitpayPaymentsRequest { notification_url: String, transaction_speed: TransactionSpeed, token: Secret<String>, + order_id: String, } impl TryFrom<&BitpayRouterData<&types::PaymentsAuthorizeRouterData>> for BitpayPaymentsRequest { @@ -279,6 +280,7 @@ fn get_crypto_specific_payment_data( ConnectorAuthType::HeaderKey { api_key } => api_key, _ => String::default().into(), }; + let order_id = item.router_data.connector_request_reference_id.clone(); Ok(BitpayPaymentsRequest { price, @@ -287,6 +289,7 @@ fn get_crypto_specific_payment_data( notification_url, transaction_speed, token, + order_id, }) }
2023-10-26T09:49:02Z
## 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 --> ### 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)? --> Make any Payment for connector Bitpay and see that you are getting "reference_id" field in the logs of payment request. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
e40a29351c7aa7b86a5684959a84f0236104cafd
juspay/hyperswitch
juspay__hyperswitch-2293
Bug: [FEATURE]: [Bambora] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index d34dda73eb6..bfcd9846292 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -48,6 +48,7 @@ pub struct BamboraBrowserInfo { #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct BamboraPaymentsRequest { + order_number: String, amount: i64, payment_method: PaymentMethod, customer_ip: Option<std::net::IpAddr>, @@ -126,6 +127,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest { }; let browser_info = item.request.get_browser_info()?; Ok(Self { + order_number: item.connector_request_reference_id.clone(), amount: item.request.amount, payment_method: PaymentMethod::Card, card: bambora_card,
2023-10-10T02:00:08Z
Addresses #2293 ## 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 use of `RequestData.request.connector_transaction_id` to `RequestData.connector_request_reference_id` for Bambora. ### 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 addresses issue #2293 by setting `connector_request_reference_id` on Bambora make payment responses. ## 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)? --> I ensured compilation was successful and existing tests ran successfully after changes were applied. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
9e450b81ca8bc4b1ddbbe2c1d732dbc58c61934e
juspay/hyperswitch
juspay__hyperswitch-2296
Bug: [FEATURE]: [Cybersource] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 3558f752841..5a3060f99eb 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -21,6 +21,7 @@ pub struct CybersourcePaymentsRequest { processing_information: ProcessingInformation, payment_information: PaymentInformation, order_information: OrderInformationWithBill, + client_reference_information: ClientReferenceInformation, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] @@ -150,10 +151,15 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest capture_options: None, }; + let client_reference_information = ClientReferenceInformation { + code: Some(item.connector_request_reference_id.clone()), + }; + Ok(Self { processing_information, payment_information, order_information, + client_reference_information, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), @@ -179,6 +185,9 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for CybersourcePaymentsRequest { }, ..Default::default() }, + client_reference_information: ClientReferenceInformation { + code: Some(value.connector_request_reference_id.clone()), + }, ..Default::default() }) } @@ -195,6 +204,9 @@ impl TryFrom<&types::RefundExecuteRouterData> for CybersourcePaymentsRequest { }, ..Default::default() }, + client_reference_information: ClientReferenceInformation { + code: Some(value.connector_request_reference_id.clone()), + }, ..Default::default() }) } @@ -278,7 +290,7 @@ pub struct CybersourcePaymentsResponse { client_reference_information: Option<ClientReferenceInformation>, } -#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)] +#[derive(Default, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct ClientReferenceInformation { code: Option<String>,
2023-10-09T13:40:40Z
Add reference with value of connector_request_reference_id in Cybersource transformers. Fixes #2296 ## 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 --> ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
550377a6c3943d9fec4ca6a8be5a5f3aafe109ab
juspay/hyperswitch
juspay__hyperswitch-2292
Bug: [FEATURE]: [Authorizedotnet] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. Please find api documentation for authorizedotnet [here](https://developer.authorize.net/api/reference/index.html#payment-transactions-charge-a-credit-card). - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 20d78729a1b..561723be46c 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -261,6 +261,7 @@ struct TransactionVoidOrCaptureRequest { pub struct AuthorizedotnetPaymentsRequest { merchant_authentication: AuthorizedotnetAuthType, transaction_request: TransactionRequest, + ref_id: String, } #[derive(Debug, Serialize)] @@ -332,6 +333,7 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> create_transaction_request: AuthorizedotnetPaymentsRequest { merchant_authentication, transaction_request, + ref_id: item.router_data.connector_request_reference_id.clone(), }, }) }
2023-10-15T08:07:18Z
…ference to the connector ## 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 --> ### 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)? --> Make any Payment for connector Authorizedotnet and see that you are getting "reference_id" field in the logs of payment request. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
94947bdb33ca4eb91daad13b2a427592d3b69851
juspay/hyperswitch
juspay__hyperswitch-2291
Bug: [FEATURE]: [Airwallex] Use `connector_request_reference_id` as reference to the connector ### :memo: Feature Description - We transmit our reference id from Hyperswitch to the connector, enabling merchants to subsequently locate the payment within the connector dashboard. - Presently, there is a lack of uniformity in this process, as some implementations employ `payment_id` while others utilize `attempt_id`. - This inconsistency arises from the fact that `payment_id` and `attempt_id` correspond to two distinct entities within our system. ### :hammer: Possible Implementation - To mitigate this confusion, we've introduced a new field called `connector_request_reference_id` in our RouterData. - This id should replace them as a reference id to the connector for payment request. - One might need to have exposure to api docs of the connector for which it is being implemented. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note : All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index ecdddfb3672..fc90743ab08 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -48,7 +48,7 @@ impl TryFrom<&types::PaymentsInitRouterData> for AirwallexIntentRequest { request_id: Uuid::new_v4().to_string(), amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, currency: item.request.currency, - merchant_order_id: item.payment_id.clone(), + merchant_order_id: item.connector_request_reference_id.clone(), }) } }
2023-10-09T23:09:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
c34f1bf36ffb3a3533dd51ac87e7f66ab0dcce79
juspay/hyperswitch
juspay__hyperswitch-2290
Bug: [REFACTOR]: [Worldpay] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 61d04a8e9f1..d31f4d65e78 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -217,7 +217,13 @@ impl From<EventType> for enums::AttemptStatus { EventType::CaptureFailed => Self::CaptureFailed, EventType::Refused => Self::Failure, EventType::Charged | EventType::SentForSettlement => Self::Charged, - _ => Self::Pending, + EventType::Cancelled + | EventType::SentForRefund + | EventType::RefundFailed + | EventType::Refunded + | EventType::Error + | EventType::Expired + | EventType::Unknown => Self::Pending, } } } @@ -227,7 +233,16 @@ impl From<EventType> for enums::RefundStatus { match value { EventType::Refunded => Self::Success, EventType::RefundFailed => Self::Failure, - _ => Self::Pending, + EventType::Authorized + | EventType::Cancelled + | EventType::Charged + | EventType::SentForRefund + | EventType::Refused + | EventType::Error + | EventType::SentForSettlement + | EventType::Expired + | EventType::CaptureFailed + | EventType::Unknown => Self::Pending, } } }
2023-10-07T11:57:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Instead of relying on a default match case `_` I have added conditions for each type in match statements. Changes are made at https://github.com/juspay/hyperswitch/blob/main/crates/router/src/connector/worldpay/transformers.rs ## Motivation and Context Closes #2290 ## Checklist - [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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
adad77f0433bb7691f4313a27e021849cd5a6c1d
juspay/hyperswitch
juspay__hyperswitch-2289
Bug: [REFACTOR]: [Worldline] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index f11c2398080..80378215a45 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -247,11 +247,19 @@ impl make_bank_redirect_request(&item.router_data.request, bank_redirect)?, )) } - _ => { - return Err( - errors::ConnectorError::NotImplemented("Payment methods".to_string()).into(), - ) - } + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::Wallet(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("worldline"), + ))?, }; let customer = @@ -393,10 +401,25 @@ fn make_bank_redirect_request( }, 809, ), - _ => { - return Err( - errors::ConnectorError::NotImplemented("Payment methods".to_string()).into(), + payments::BankRedirectData::BancontactCard { .. } + | payments::BankRedirectData::Bizum {} + | payments::BankRedirectData::Blik { .. } + | payments::BankRedirectData::Eps { .. } + | payments::BankRedirectData::Interac { .. } + | payments::BankRedirectData::OnlineBankingCzechRepublic { .. } + | payments::BankRedirectData::OnlineBankingFinland { .. } + | payments::BankRedirectData::OnlineBankingPoland { .. } + | payments::BankRedirectData::OnlineBankingSlovakia { .. } + | payments::BankRedirectData::OpenBankingUk { .. } + | payments::BankRedirectData::Przelewy24 { .. } + | payments::BankRedirectData::Sofort { .. } + | payments::BankRedirectData::Trustly { .. } + | payments::BankRedirectData::OnlineBankingFpx { .. } + | payments::BankRedirectData::OnlineBankingThailand { .. } => { + return Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("worldline"), ) + .into()) } }; Ok(RedirectPaymentMethod {
2023-10-24T09:39: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 --> https://github.com/juspay/hyperswitch/issues/2289 ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
eaa972052024678ade122eec14261f9f33788e45
juspay/hyperswitch
juspay__hyperswitch-2288
Bug: [REFACTOR]: [Tsys] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs index 83134568c05..a3bd1c4a074 100644 --- a/crates/router/src/connector/tsys/transformers.rs +++ b/crates/router/src/connector/tsys/transformers.rs @@ -3,7 +3,7 @@ use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{CardData, PaymentsAuthorizeRequestData, RefundsRequestData}, + connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RefundsRequestData}, core::errors, types::{ self, api, @@ -66,7 +66,20 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest { Ok(Self::Auth(auth_data)) } } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::Wallet(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("tsys"), + ))?, } } }
2023-10-23T21:26:08Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- https://github.com/juspay/hyperswitch/issues/2288 --> Resolves: #2288 ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
eaa972052024678ade122eec14261f9f33788e45
juspay/hyperswitch
juspay__hyperswitch-2287
Bug: [REFACTOR]: [Trustpay] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/Cargo.lock b/Cargo.lock index cca3b6f58d9..9e026101d1a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -393,6 +393,7 @@ dependencies = [ "serde", "serde_json", "strum 0.24.1", + "thiserror", "time 0.3.22", "url", "utoipa", @@ -471,18 +472,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "async-bb8-diesel" -version = "0.1.0" -source = "git+https://github.com/juspay/async-bb8-diesel?rev=9a71d142726dbc33f41c1fd935ddaa79841c7be5#9a71d142726dbc33f41c1fd935ddaa79841c7be5" -dependencies = [ - "async-trait", - "bb8", - "diesel", - "thiserror", - "tokio", -] - [[package]] name = "async-bb8-diesel" version = "0.1.0" @@ -735,39 +724,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "aws-sdk-s3" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "392b9811ca489747ac84349790e49deaa1f16631949e7dd4156000251c260eae" -dependencies = [ - "aws-credential-types", - "aws-endpoint", - "aws-http", - "aws-sig-auth", - "aws-sigv4", - "aws-smithy-async", - "aws-smithy-checksums", - "aws-smithy-client", - "aws-smithy-eventstream", - "aws-smithy-http", - "aws-smithy-http-tower", - "aws-smithy-json", - "aws-smithy-types", - "aws-smithy-xml", - "aws-types", - "bytes", - "http", - "http-body", - "once_cell", - "percent-encoding", - "regex", - "tokio-stream", - "tower", - "tracing", - "url", -] - [[package]] name = "aws-sdk-s3" version = "0.28.0" @@ -1204,7 +1160,16 @@ dependencies = [ "cc", "cfg-if", "constant_time_eq", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "block-buffer" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" +dependencies = [ + "generic-array", ] [[package]] @@ -1853,9 +1818,9 @@ dependencies = [ name = "diesel_models" version = "0.1.0" dependencies = [ - "async-bb8-diesel 0.1.0 (git+https://github.com/oxidecomputer/async-bb8-diesel?rev=be3d9bce50051d8c0e0c06078e8066cc27db3001)", + "async-bb8-diesel", "aws-config", - "aws-sdk-s3 0.28.0", + "aws-sdk-s3", "common_enums", "common_utils", "diesel", @@ -1882,13 +1847,22 @@ dependencies = [ "syn 2.0.29", ] +[[package]] +name = "digest" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +dependencies = [ + "generic-array", +] + [[package]] name = "digest" version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", + "block-buffer 0.10.4", "crypto-common", "subtle", ] @@ -1940,7 +1914,7 @@ checksum = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257" name = "drainer" version = "0.1.0" dependencies = [ - "async-bb8-diesel 0.1.0 (git+https://github.com/oxidecomputer/async-bb8-diesel?rev=be3d9bce50051d8c0e0c06078e8066cc27db3001)", + "async-bb8-diesel", "bb8", "clap", "common_utils", @@ -1988,20 +1962,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" dependencies = [ "atty", - "humantime 1.3.0", - "log", - "regex", - "termcolor", -] - -[[package]] -name = "env_logger" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" -dependencies = [ - "humantime 2.1.0", - "is-terminal", + "humantime", "log", "regex", "termcolor", @@ -2192,7 +2153,7 @@ dependencies = [ "rand 0.8.5", "redis-protocol", "semver", - "sha-1", + "sha-1 0.10.1", "tokio", "tokio-stream", "tokio-util", @@ -2522,7 +2483,7 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -2589,12 +2550,6 @@ dependencies = [ "quick-error", ] -[[package]] -name = "humantime" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" - [[package]] name = "hyper" version = "0.14.27" @@ -2779,18 +2734,6 @@ version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12b6ee2129af8d4fb011108c73d99a1b83a85977f23b82460c0ae2e25bb4b57f" -[[package]] -name = "is-terminal" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adcf93614601c8129ddf72e2d5633df827ba6551541c6d8c59520a371475be1f" -dependencies = [ - "hermit-abi 0.3.1", - "io-lifetimes", - "rustix", - "windows-sys 0.48.0", -] - [[package]] name = "itertools" version = "0.10.5" @@ -3070,7 +3013,7 @@ version = "0.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6365506850d44bff6e2fbcb5176cf63650e48bd45ef2fe2665ae1570e0f4b9ca" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -3321,6 +3264,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44d11de466f4a3006fe8a5e7ec84e93b79c70cb992ae0aa0eb631ad2df8abfe2" +[[package]] +name = "opaque-debug" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" + [[package]] name = "openssl" version = "0.10.55" @@ -3680,7 +3629,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "926d36b9553851b8b0005f1275891b392ee4d2d833852c417ed025477350fb9d" dependencies = [ - "env_logger 0.7.1", + "env_logger", "log", ] @@ -4134,11 +4083,11 @@ dependencies = [ "actix-rt", "actix-web", "api_models", - "async-bb8-diesel 0.1.0 (git+https://github.com/oxidecomputer/async-bb8-diesel?rev=be3d9bce50051d8c0e0c06078e8066cc27db3001)", + "async-bb8-diesel", "async-trait", "awc", "aws-config", - "aws-sdk-s3 0.28.0", + "aws-sdk-s3", "base64 0.21.2", "bb8", "blake3", @@ -4151,6 +4100,7 @@ dependencies = [ "derive_deref", "diesel", "diesel_models", + "digest 0.9.0", "dyn-clone", "encoding_rs", "error-stack", @@ -4189,6 +4139,7 @@ dependencies = [ "serde_urlencoded", "serde_with", "serial_test", + "sha-1 0.9.8", "signal-hook", "signal-hook-tokio", "storage_impl", @@ -4428,36 +4379,19 @@ dependencies = [ name = "scheduler" version = "0.1.0" dependencies = [ - "actix-multipart", - "actix-rt", - "actix-web", - "api_models", - "async-bb8-diesel 0.1.0 (git+https://github.com/juspay/async-bb8-diesel?rev=9a71d142726dbc33f41c1fd935ddaa79841c7be5)", "async-trait", - "aws-config", - "aws-sdk-s3 0.25.1", - "cards", - "clap", "common_utils", - "diesel", "diesel_models", - "dyn-clone", - "env_logger 0.10.0", "error-stack", "external_services", - "frunk", - "frunk_core", "futures", - "infer 0.13.0", "masking", "once_cell", "rand 0.8.5", "redis_interface", - "router_derive", "router_env", "serde", "serde_json", - "signal-hook", "signal-hook-tokio", "storage_impl", "strum 0.24.1", @@ -4678,6 +4612,19 @@ dependencies = [ "syn 2.0.29", ] +[[package]] +name = "sha-1" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99cd6713db3cf16b6c84e06321e049a9b9f699826e16096d23bbcc44d15d51a6" +dependencies = [ + "block-buffer 0.9.0", + "cfg-if", + "cpufeatures", + "digest 0.9.0", + "opaque-debug", +] + [[package]] name = "sha-1" version = "0.10.1" @@ -4686,7 +4633,7 @@ checksum = "f5058ada175748e33390e40e872bd0fe59a19f265d0158daa551c5a88a76009c" dependencies = [ "cfg-if", "cpufeatures", - "digest", + "digest 0.10.7", ] [[package]] @@ -4697,7 +4644,7 @@ checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" dependencies = [ "cfg-if", "cpufeatures", - "digest", + "digest 0.10.7", ] [[package]] @@ -4708,7 +4655,7 @@ checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0" dependencies = [ "cfg-if", "cpufeatures", - "digest", + "digest 0.10.7", ] [[package]] @@ -4824,7 +4771,7 @@ version = "0.1.0" dependencies = [ "actix-web", "api_models", - "async-bb8-diesel 0.1.0 (git+https://github.com/oxidecomputer/async-bb8-diesel?rev=be3d9bce50051d8c0e0c06078e8066cc27db3001)", + "async-bb8-diesel", "async-trait", "bb8", "bytes", diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index e9ef7f4c288..5ca4bd1ac3d 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -238,7 +238,23 @@ impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod { api_models::payments::BankRedirectData::Ideal { .. } => Ok(Self::IDeal), api_models::payments::BankRedirectData::Sofort { .. } => Ok(Self::Sofort), api_models::payments::BankRedirectData::Blik { .. } => Ok(Self::Blik), - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + api_models::payments::BankRedirectData::BancontactCard { .. } + | api_models::payments::BankRedirectData::Bizum {} + | api_models::payments::BankRedirectData::Interac { .. } + | api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { .. } + | api_models::payments::BankRedirectData::OnlineBankingFinland { .. } + | api_models::payments::BankRedirectData::OnlineBankingPoland { .. } + | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. } + | api_models::payments::BankRedirectData::OpenBankingUk { .. } + | api_models::payments::BankRedirectData::Przelewy24 { .. } + | api_models::payments::BankRedirectData::Trustly { .. } + | api_models::payments::BankRedirectData::OnlineBankingFpx { .. } + | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("trustpay"), + ) + .into()) + } } } } @@ -419,7 +435,20 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for Trust auth, ) } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::Wallet(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("trustpay"), + ) + .into()), } } }
2023-10-06T16:14:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Handling the unhandled variants for trustpay Issue #2287 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ba2efac4fa2af22f81b0841350a334bc36e91022
juspay/hyperswitch
juspay__hyperswitch-2286
Bug: [REFACTOR]: [Square] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index 01ed507bf34..54a7c461dbf 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -23,7 +23,10 @@ impl TryFrom<(&types::TokenizationRouterData, BankDebitData)> for SquareTokenReq "Payment Method".to_string(), )) .into_report(), - _ => Err(errors::ConnectorError::NotSupported { + + BankDebitData::SepaBankDebit { .. } + | BankDebitData::BecsBankDebit { .. } + | BankDebitData::BacsBankDebit { .. } => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_data), connector: "Square", })?, @@ -85,7 +88,14 @@ impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequ errors::ConnectorError::NotImplemented("Payment Method".to_string()), ) .into_report(), - _ => Err(errors::ConnectorError::NotSupported { + + PayLaterData::KlarnaRedirect { .. } + | PayLaterData::KlarnaSdk { .. } + | PayLaterData::AffirmRedirect { .. } + | PayLaterData::PayBrightRedirect { .. } + | PayLaterData::WalleyRedirect { .. } + | PayLaterData::AlmaRedirect { .. } + | PayLaterData::AtomeRedirect { .. } => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_data), connector: "Square", })?, @@ -106,7 +116,31 @@ impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenReques "Payment Method".to_string(), )) .into_report(), - _ => Err(errors::ConnectorError::NotSupported { + + WalletData::AliPayQr(_) + | WalletData::AliPayRedirect(_) + | WalletData::AliPayHkRedirect(_) + | WalletData::MomoRedirect(_) + | WalletData::KakaoPayRedirect(_) + | WalletData::GoPayRedirect(_) + | WalletData::GcashRedirect(_) + | WalletData::ApplePayRedirect(_) + | WalletData::ApplePayThirdPartySdk(_) + | WalletData::DanaRedirect {} + | WalletData::GooglePayRedirect(_) + | WalletData::GooglePayThirdPartySdk(_) + | WalletData::MbWayRedirect(_) + | WalletData::MobilePayRedirect(_) + | WalletData::PaypalRedirect(_) + | WalletData::PaypalSdk(_) + | WalletData::SamsungPay(_) + | WalletData::TwintRedirect {} + | WalletData::VippsRedirect {} + | WalletData::TouchNGoRedirect(_) + | WalletData::WeChatPayRedirect(_) + | WalletData::WeChatPayQr(_) + | WalletData::CashappQr(_) + | WalletData::SwishQr(_) => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_data), connector: "Square", })?, @@ -295,7 +329,14 @@ impl TryFrom<&types::ConnectorAuthType> for SquareAuthType { api_key: api_key.to_owned(), key1: key1.to_owned(), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + + types::ConnectorAuthType::HeaderKey { .. } + | types::ConnectorAuthType::SignatureKey { .. } + | types::ConnectorAuthType::MultiAuthKey { .. } + | types::ConnectorAuthType::CurrencyAuthKey { .. } + | types::ConnectorAuthType::NoKey { .. } => { + Err(errors::ConnectorError::FailedToObtainAuthType.into()) + } } } }
2023-10-26T14:35:57Z
## 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 --> - Fix issue #2286 - Changes to be made : Remove default case handling - File changed: ```transformers.rs``` (crates/router/src/connector/square/transformers.rs) ### 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/2286 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> No test cases. As In this PR only error message have been populated for all default cases. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
88e1f29dae13622bc58b8f5df1cd84b929b28ac6
juspay/hyperswitch
juspay__hyperswitch-2283
Bug: [REFACTOR]: [PowerTranz] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index 4032f8019b0..5bbfe094352 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -1,6 +1,7 @@ use api_models::payments::Card; use common_utils::pii::Email; use diesel_models::enums::RefundStatus; +use error_stack::IntoReport; use masking::Secret; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -101,9 +102,22 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let source = match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(card) => Ok(Source::from(&card)), - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), - )), + api::PaymentMethodData::Wallet(_) + | api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "powertranz", + }) + .into_report(), }?; // let billing_address = get_address_details(&item.address.billing, &item.request.email); // let shipping_address = get_address_details(&item.address.shipping, &item.request.email);
2023-10-11T13:10: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 --> ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
31431e41357d4d3d12668fa0d678cce0b3d86611
juspay/hyperswitch
juspay__hyperswitch-2282
Bug: [REFACTOR]: [Payme] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 4ced1a9bcda..1b7ce27439b 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -651,7 +651,20 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest { language: LANGUAGE.to_string(), }) } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::Wallet(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("payme"), + ))?, } } }
2023-10-29T12:15:07Z
## Type of Change - [x] Refactoring ## Description This PR removes the default case handling and adds error handling for all the available cases. Fixes #2282 ## How did you test it? No test cases. As In this PR only error message have been populated for all default cases. ## Checklist - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code
4afe552563c6a0cb9544a9a2f870bb9d07d7cf18
juspay/hyperswitch
juspay__hyperswitch-2281
Bug: [REFACTOR]: [Payeezy] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index 98e8ea12c00..efcd1b36d5b 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -37,11 +37,14 @@ impl TryFrom<utils::CardIssuer> for PayeezyCardType { utils::CardIssuer::Master => Ok(Self::Mastercard), utils::CardIssuer::Discover => Ok(Self::Discover), utils::CardIssuer::Visa => Ok(Self::Visa), - _ => Err(errors::ConnectorError::NotSupported { - message: issuer.to_string(), - connector: "Payeezy", + + utils::CardIssuer::Maestro | utils::CardIssuer::DinersClub | utils::CardIssuer::JCB => { + Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Payeezy", + } + .into()) } - .into()), } } } @@ -97,7 +100,20 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayeezyPaymentsRequest { fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { match item.payment_method { diesel_models::enums::PaymentMethod::Card => get_card_specific_payment_data(item), - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + + diesel_models::enums::PaymentMethod::CardRedirect + | diesel_models::enums::PaymentMethod::PayLater + | diesel_models::enums::PaymentMethod::Wallet + | diesel_models::enums::PaymentMethod::BankRedirect + | diesel_models::enums::PaymentMethod::BankTransfer + | diesel_models::enums::PaymentMethod::Crypto + | diesel_models::enums::PaymentMethod::BankDebit + | diesel_models::enums::PaymentMethod::Reward + | diesel_models::enums::PaymentMethod::Upi + | diesel_models::enums::PaymentMethod::Voucher + | diesel_models::enums::PaymentMethod::GiftCard => { + Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) + } } } } @@ -165,7 +181,10 @@ fn get_transaction_type_and_stored_creds( Some(diesel_models::enums::CaptureMethod::Automatic) => { Ok((PayeezyTransactionType::Purchase, None)) } - _ => Err(errors::ConnectorError::FlowNotSupported { + + Some(diesel_models::enums::CaptureMethod::ManualMultiple) + | Some(diesel_models::enums::CaptureMethod::Scheduled) + | None => Err(errors::ConnectorError::FlowNotSupported { flow: item.request.capture_method.unwrap_or_default().to_string(), connector: "Payeezy".to_string(), }), @@ -196,7 +215,23 @@ fn get_payment_method_data( }; Ok(PayeezyPaymentMethod::PayeezyCard(payeezy_card)) } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::Wallet(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Payeezy", + } + .into()), } } @@ -383,7 +418,7 @@ impl ForeignFrom<(PayeezyPaymentStatus, PayeezyTransactionType)> for enums::Atte | PayeezyTransactionType::Purchase | PayeezyTransactionType::Recurring => Self::Charged, PayeezyTransactionType::Void => Self::Voided, - _ => Self::Pending, + PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => Self::Pending, }, PayeezyPaymentStatus::Declined | PayeezyPaymentStatus::NotProcessed => match method { PayeezyTransactionType::Capture => Self::CaptureFailed, @@ -391,7 +426,7 @@ impl ForeignFrom<(PayeezyPaymentStatus, PayeezyTransactionType)> for enums::Atte | PayeezyTransactionType::Purchase | PayeezyTransactionType::Recurring => Self::AuthorizationFailed, PayeezyTransactionType::Void => Self::VoidFailed, - _ => Self::Pending, + PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => Self::Pending, }, } }
2023-10-27T14:47:44Z
## 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 --> - Fix issue #2281 - Changes to be made : Remove default case handling - File changed: ```transformers.rs``` (crates/router/src/connector/payeezy/transformers.rs) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> No test cases. As In this PR only error message have been populated for all default cases. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ca77c7ce3c6b806ff60e83725cc4e50855422037
juspay/hyperswitch
juspay__hyperswitch-2279
Bug: [REFACTOR]: [Opayo] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index d828232dbc1..41bcc1500ed 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -2,7 +2,7 @@ use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::PaymentsAuthorizeRequestData, + connector::utils::{self, PaymentsAuthorizeRequestData}, core::errors, types::{self, api, storage::enums}, }; @@ -41,7 +41,21 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest { card, }) } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::Wallet(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Opayo"), + ) + .into()), } } }
2023-10-25T12:28:59Z
## 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 --> #2279 ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
27b97626245cab12dd9aefb4d85a77b5c913dba0
juspay/hyperswitch
juspay__hyperswitch-2278
Bug: [REFACTOR]: [Nuvei] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 2fd1a9c272f..88ebe1d8dbe 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -490,11 +490,145 @@ impl TryFrom<api_models::enums::BankNames> for NuveiBIC { api_models::enums::BankNames::TriodosBank => Ok(Self::TriodosBank), api_models::enums::BankNames::VanLanschot => Ok(Self::VanLanschotBankiers), api_models::enums::BankNames::Moneyou => Ok(Self::Moneyou), - _ => Err(errors::ConnectorError::FlowNotSupported { - flow: bank.to_string(), - connector: "Nuvei".to_string(), + + api_models::enums::BankNames::AmericanExpress + | api_models::enums::BankNames::AffinBank + | api_models::enums::BankNames::AgroBank + | api_models::enums::BankNames::AllianceBank + | api_models::enums::BankNames::AmBank + | api_models::enums::BankNames::BankOfAmerica + | api_models::enums::BankNames::BankIslam + | api_models::enums::BankNames::BankMuamalat + | api_models::enums::BankNames::BankRakyat + | api_models::enums::BankNames::BankSimpananNasional + | api_models::enums::BankNames::Barclays + | api_models::enums::BankNames::BlikPSP + | api_models::enums::BankNames::CapitalOne + | api_models::enums::BankNames::Chase + | api_models::enums::BankNames::Citi + | api_models::enums::BankNames::CimbBank + | api_models::enums::BankNames::Discover + | api_models::enums::BankNames::NavyFederalCreditUnion + | api_models::enums::BankNames::PentagonFederalCreditUnion + | api_models::enums::BankNames::SynchronyBank + | api_models::enums::BankNames::WellsFargo + | api_models::enums::BankNames::Handelsbanken + | api_models::enums::BankNames::HongLeongBank + | api_models::enums::BankNames::HsbcBank + | api_models::enums::BankNames::KuwaitFinanceHouse + | api_models::enums::BankNames::Regiobank + | api_models::enums::BankNames::Revolut + | api_models::enums::BankNames::ArzteUndApothekerBank + | api_models::enums::BankNames::AustrianAnadiBankAg + | api_models::enums::BankNames::BankAustria + | api_models::enums::BankNames::Bank99Ag + | api_models::enums::BankNames::BankhausCarlSpangler + | api_models::enums::BankNames::BankhausSchelhammerUndSchatteraAg + | api_models::enums::BankNames::BankMillennium + | api_models::enums::BankNames::BankPEKAOSA + | api_models::enums::BankNames::BawagPskAg + | api_models::enums::BankNames::BksBankAg + | api_models::enums::BankNames::BrullKallmusBankAg + | api_models::enums::BankNames::BtvVierLanderBank + | api_models::enums::BankNames::CapitalBankGraweGruppeAg + | api_models::enums::BankNames::CeskaSporitelna + | api_models::enums::BankNames::Dolomitenbank + | api_models::enums::BankNames::EasybankAg + | api_models::enums::BankNames::EPlatbyVUB + | api_models::enums::BankNames::ErsteBankUndSparkassen + | api_models::enums::BankNames::FrieslandBank + | api_models::enums::BankNames::HypoAlpeadriabankInternationalAg + | api_models::enums::BankNames::HypoNoeLbFurNiederosterreichUWien + | api_models::enums::BankNames::HypoOberosterreichSalzburgSteiermark + | api_models::enums::BankNames::HypoTirolBankAg + | api_models::enums::BankNames::HypoVorarlbergBankAg + | api_models::enums::BankNames::HypoBankBurgenlandAktiengesellschaft + | api_models::enums::BankNames::KomercniBanka + | api_models::enums::BankNames::MBank + | api_models::enums::BankNames::MarchfelderBank + | api_models::enums::BankNames::Maybank + | api_models::enums::BankNames::OberbankAg + | api_models::enums::BankNames::OsterreichischeArzteUndApothekerbank + | api_models::enums::BankNames::OcbcBank + | api_models::enums::BankNames::PayWithING + | api_models::enums::BankNames::PlaceZIPKO + | api_models::enums::BankNames::PlatnoscOnlineKartaPlatnicza + | api_models::enums::BankNames::PosojilnicaBankEGen + | api_models::enums::BankNames::PostovaBanka + | api_models::enums::BankNames::PublicBank + | api_models::enums::BankNames::RaiffeisenBankengruppeOsterreich + | api_models::enums::BankNames::RhbBank + | api_models::enums::BankNames::SchelhammerCapitalBankAg + | api_models::enums::BankNames::StandardCharteredBank + | api_models::enums::BankNames::SchoellerbankAg + | api_models::enums::BankNames::SpardaBankWien + | api_models::enums::BankNames::SporoPay + | api_models::enums::BankNames::SantanderPrzelew24 + | api_models::enums::BankNames::TatraPay + | api_models::enums::BankNames::Viamo + | api_models::enums::BankNames::VolksbankGruppe + | api_models::enums::BankNames::VolkskreditbankAg + | api_models::enums::BankNames::VrBankBraunau + | api_models::enums::BankNames::UobBank + | api_models::enums::BankNames::PayWithAliorBank + | api_models::enums::BankNames::BankiSpoldzielcze + | api_models::enums::BankNames::PayWithInteligo + | api_models::enums::BankNames::BNPParibasPoland + | api_models::enums::BankNames::BankNowySA + | api_models::enums::BankNames::CreditAgricole + | api_models::enums::BankNames::PayWithBOS + | api_models::enums::BankNames::PayWithCitiHandlowy + | api_models::enums::BankNames::PayWithPlusBank + | api_models::enums::BankNames::ToyotaBank + | api_models::enums::BankNames::VeloBank + | api_models::enums::BankNames::ETransferPocztowy24 + | api_models::enums::BankNames::PlusBank + | api_models::enums::BankNames::EtransferPocztowy24 + | api_models::enums::BankNames::BankiSpbdzielcze + | api_models::enums::BankNames::BankNowyBfgSa + | api_models::enums::BankNames::GetinBank + | api_models::enums::BankNames::Blik + | api_models::enums::BankNames::NoblePay + | api_models::enums::BankNames::IdeaBank + | api_models::enums::BankNames::EnveloBank + | api_models::enums::BankNames::NestPrzelew + | api_models::enums::BankNames::MbankMtransfer + | api_models::enums::BankNames::Inteligo + | api_models::enums::BankNames::PbacZIpko + | api_models::enums::BankNames::BnpParibas + | api_models::enums::BankNames::BankPekaoSa + | api_models::enums::BankNames::VolkswagenBank + | api_models::enums::BankNames::AliorBank + | api_models::enums::BankNames::Boz + | api_models::enums::BankNames::BangkokBank + | api_models::enums::BankNames::KrungsriBank + | api_models::enums::BankNames::KrungThaiBank + | api_models::enums::BankNames::TheSiamCommercialBank + | api_models::enums::BankNames::KasikornBank + | api_models::enums::BankNames::OpenBankSuccess + | api_models::enums::BankNames::OpenBankFailure + | api_models::enums::BankNames::OpenBankCancelled + | api_models::enums::BankNames::Aib + | api_models::enums::BankNames::BankOfScotland + | api_models::enums::BankNames::DanskeBank + | api_models::enums::BankNames::FirstDirect + | api_models::enums::BankNames::FirstTrust + | api_models::enums::BankNames::Halifax + | api_models::enums::BankNames::Lloyds + | api_models::enums::BankNames::Monzo + | api_models::enums::BankNames::NatWest + | api_models::enums::BankNames::NationwideBank + | api_models::enums::BankNames::RoyalBankOfScotland + | api_models::enums::BankNames::Starling + | api_models::enums::BankNames::TsbBank + | api_models::enums::BankNames::TescoBank + | api_models::enums::BankNames::UlsterBank => { + Err(errors::ConnectorError::NotSupported { + message: bank.to_string(), + connector: "Nuvei", + } + .into()) } - .into()), } } }
2023-10-13T18:46:35Z
## 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 --> - Fix issue #2278 - Changes to be made : Remove default case handling - Added all the ```Banknames``` (which are not ```NuveiBIC``` ) against the default case - File changed: **```transformers.rs```** (crates/router/src/connector/nuvei/transformers.rs) ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5d88dbc92ce470c951717debe246e182b3fe5656
juspay/hyperswitch
juspay__hyperswitch-2277
Bug: [REFACTOR]: [Noon] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index cde6de2e43b..4a2128f7ec6 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -245,13 +245,51 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { return_url: item.request.get_router_return_url()?, })) } - _ => Err(errors::ConnectorError::NotImplemented( - "Wallets".to_string(), - )), + api_models::payments::WalletData::AliPayQr(_) + | api_models::payments::WalletData::AliPayRedirect(_) + | api_models::payments::WalletData::AliPayHkRedirect(_) + | api_models::payments::WalletData::MomoRedirect(_) + | api_models::payments::WalletData::KakaoPayRedirect(_) + | api_models::payments::WalletData::GoPayRedirect(_) + | api_models::payments::WalletData::GcashRedirect(_) + | api_models::payments::WalletData::ApplePayRedirect(_) + | api_models::payments::WalletData::ApplePayThirdPartySdk(_) + | api_models::payments::WalletData::DanaRedirect {} + | api_models::payments::WalletData::GooglePayRedirect(_) + | api_models::payments::WalletData::GooglePayThirdPartySdk(_) + | api_models::payments::WalletData::MbWayRedirect(_) + | api_models::payments::WalletData::MobilePayRedirect(_) + | api_models::payments::WalletData::PaypalSdk(_) + | api_models::payments::WalletData::SamsungPay(_) + | api_models::payments::WalletData::TwintRedirect {} + | api_models::payments::WalletData::VippsRedirect {} + | api_models::payments::WalletData::TouchNGoRedirect(_) + | api_models::payments::WalletData::WeChatPayRedirect(_) + | api_models::payments::WalletData::WeChatPayQr(_) + | api_models::payments::WalletData::CashappQr(_) + | api_models::payments::WalletData::SwishQr(_) => { + Err(errors::ConnectorError::NotSupported { + message: conn_utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Noon", + }) + } }, - _ => Err(errors::ConnectorError::NotImplemented( - "Payment methods".to_string(), - )), + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment {} + | api::PaymentMethodData::Reward {} + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => { + Err(errors::ConnectorError::NotSupported { + message: conn_utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Noon", + }) + } }?, Some(item.request.currency), item.request.order_category.clone(),
2023-10-25T00:59:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Addresses Issue #2277 - Modified `crates/router/src/connector/noon/transformers.rs` - Convert `NotImplemented` to `NotSupported` in default case ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? No test cases. As In this PR only error message have been populated for all default cases. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
2815443c1b147e005a2384ff817292b1845a9f88
juspay/hyperswitch
juspay__hyperswitch-2276
Bug: [REFACTOR]: [NMI] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index a57ac4271d0..3f64ff9eaca 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -112,14 +112,51 @@ impl TryFrom<&api_models::payments::PaymentMethodData> for PaymentMethod { api_models::payments::WalletData::ApplePay(ref applepay_data) => { Ok(Self::from(applepay_data)) } - _ => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - )) - .into_report(), + api_models::payments::WalletData::AliPayQr(_) + | api_models::payments::WalletData::AliPayRedirect(_) + | api_models::payments::WalletData::AliPayHkRedirect(_) + | api_models::payments::WalletData::MomoRedirect(_) + | api_models::payments::WalletData::KakaoPayRedirect(_) + | api_models::payments::WalletData::GoPayRedirect(_) + | api_models::payments::WalletData::GcashRedirect(_) + | api_models::payments::WalletData::ApplePayRedirect(_) + | api_models::payments::WalletData::ApplePayThirdPartySdk(_) + | api_models::payments::WalletData::DanaRedirect {} + | api_models::payments::WalletData::GooglePayRedirect(_) + | api_models::payments::WalletData::GooglePayThirdPartySdk(_) + | api_models::payments::WalletData::MbWayRedirect(_) + | api_models::payments::WalletData::MobilePayRedirect(_) + | api_models::payments::WalletData::PaypalRedirect(_) + | api_models::payments::WalletData::PaypalSdk(_) + | api_models::payments::WalletData::SamsungPay(_) + | api_models::payments::WalletData::TwintRedirect {} + | api_models::payments::WalletData::VippsRedirect {} + | api_models::payments::WalletData::TouchNGoRedirect(_) + | api_models::payments::WalletData::WeChatPayRedirect(_) + | api_models::payments::WalletData::WeChatPayQr(_) + | api_models::payments::WalletData::CashappQr(_) + | api_models::payments::WalletData::SwishQr(_) => { + Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "nmi", + }) + .into_report() + } }, - _ => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - )) + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "nmi", + }) .into_report(), } }
2023-10-05T15:12:18Z
## 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 --> Adds the error handles for all unhandled variants ### 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). --> Wanted to contribute to open source ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
414996592b3016bfa9f3399319c6e02ccd333c68
juspay/hyperswitch
juspay__hyperswitch-2275
Bug: [REFACTOR]: [Nexi nets] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 897d8f639d3..2af3ee0a1bb 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -9,7 +9,7 @@ use url::Url; use crate::{ connector::utils::{ - CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, WalletData, + self, CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, WalletData, }, consts, core::errors, @@ -597,12 +597,35 @@ fn get_payment_details_and_product( api_models::payments::BankRedirectData::Sofort { .. } => { Ok((None, NexinetsProduct::Sofort)) } - _ => Err(errors::ConnectorError::NotImplemented( - "Payment methods".to_string(), - ))?, + api_models::payments::BankRedirectData::BancontactCard { .. } + | api_models::payments::BankRedirectData::Blik { .. } + | api_models::payments::BankRedirectData::Bizum { .. } + | api_models::payments::BankRedirectData::Interac { .. } + | api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { .. } + | api_models::payments::BankRedirectData::OnlineBankingFinland { .. } + | api_models::payments::BankRedirectData::OnlineBankingPoland { .. } + | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. } + | api_models::payments::BankRedirectData::OpenBankingUk { .. } + | api_models::payments::BankRedirectData::Przelewy24 { .. } + | api_models::payments::BankRedirectData::Trustly { .. } + | api_models::payments::BankRedirectData::OnlineBankingFpx { .. } + | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("nexinets"), + ))? + } }, - _ => Err(errors::ConnectorError::NotImplemented( - "Payment methods".to_string(), + PaymentMethodData::CardRedirect(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("nexinets"), ))?, } } @@ -677,9 +700,34 @@ fn get_wallet_details( ))), NexinetsProduct::Applepay, )), - _ => Err(errors::ConnectorError::NotImplemented( - "Payment methods".to_string(), - ))?, + api_models::payments::WalletData::AliPayQr(_) + | api_models::payments::WalletData::AliPayRedirect(_) + | api_models::payments::WalletData::AliPayHkRedirect(_) + | api_models::payments::WalletData::MomoRedirect(_) + | api_models::payments::WalletData::KakaoPayRedirect(_) + | api_models::payments::WalletData::GoPayRedirect(_) + | api_models::payments::WalletData::GcashRedirect(_) + | api_models::payments::WalletData::ApplePayRedirect(_) + | api_models::payments::WalletData::ApplePayThirdPartySdk(_) + | api_models::payments::WalletData::DanaRedirect { .. } + | api_models::payments::WalletData::GooglePay(_) + | api_models::payments::WalletData::GooglePayRedirect(_) + | api_models::payments::WalletData::GooglePayThirdPartySdk(_) + | api_models::payments::WalletData::MbWayRedirect(_) + | api_models::payments::WalletData::MobilePayRedirect(_) + | api_models::payments::WalletData::PaypalSdk(_) + | api_models::payments::WalletData::SamsungPay(_) + | api_models::payments::WalletData::TwintRedirect { .. } + | api_models::payments::WalletData::VippsRedirect { .. } + | api_models::payments::WalletData::TouchNGoRedirect(_) + | api_models::payments::WalletData::WeChatPayRedirect(_) + | api_models::payments::WalletData::WeChatPayQr(_) + | api_models::payments::WalletData::CashappQr(_) + | api_models::payments::WalletData::SwishQr(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("nexinets"), + ))? + } } }
2023-10-19T03:44:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- https://github.com/juspay/hyperswitch/issues/2275 --> ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cc0b42263257b6cf6c7f94350442a74d3c02750b
juspay/hyperswitch
juspay__hyperswitch-2274
Bug: [REFACTOR]: [Multisafepay] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index a8366fadf81..385c85e0aa6 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -229,11 +229,13 @@ impl TryFrom<utils::CardIssuer> for Gateway { utils::CardIssuer::Maestro => Ok(Self::Maestro), utils::CardIssuer::Discover => Ok(Self::Discover), utils::CardIssuer::Visa => Ok(Self::Visa), - _ => Err(errors::ConnectorError::NotSupported { - message: issuer.to_string(), - connector: "Multisafe pay", + utils::CardIssuer::DinersClub | utils::CardIssuer::JCB => { + Err(errors::ConnectorError::NotSupported { + message: issuer.to_string(), + connector: "Multisafe pay", + } + .into()) } - .into()), } } } @@ -247,8 +249,31 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques api::PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { api::WalletData::GooglePay(_) => Type::Direct, api::WalletData::PaypalRedirect(_) => Type::Redirect, - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), + api::WalletData::AliPayQr(_) + | api::WalletData::AliPayRedirect(_) + | api::WalletData::AliPayHkRedirect(_) + | api::WalletData::MomoRedirect(_) + | api::WalletData::KakaoPayRedirect(_) + | api::WalletData::GoPayRedirect(_) + | api::WalletData::GcashRedirect(_) + | api::WalletData::ApplePay(_) + | api::WalletData::ApplePayRedirect(_) + | api::WalletData::ApplePayThirdPartySdk(_) + | api::WalletData::DanaRedirect {} + | api::WalletData::GooglePayRedirect(_) + | api::WalletData::GooglePayThirdPartySdk(_) + | api::WalletData::MbWayRedirect(_) + | api::WalletData::MobilePayRedirect(_) + | api::WalletData::PaypalSdk(_) + | api::WalletData::SamsungPay(_) + | api::WalletData::TwintRedirect {} + | api::WalletData::VippsRedirect {} + | api::WalletData::TouchNGoRedirect(_) + | api::WalletData::WeChatPayRedirect(_) + | api::WalletData::WeChatPayQr(_) + | api::WalletData::CashappQr(_) + | api::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }, api::PaymentMethodData::PayLater(ref _paylater) => Type::Redirect, @@ -262,8 +287,31 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques api::PaymentMethodData::Wallet(ref wallet_data) => Some(match wallet_data { api::WalletData::GooglePay(_) => Gateway::Googlepay, api::WalletData::PaypalRedirect(_) => Gateway::Paypal, - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), + api::WalletData::AliPayQr(_) + | api::WalletData::AliPayRedirect(_) + | api::WalletData::AliPayHkRedirect(_) + | api::WalletData::MomoRedirect(_) + | api::WalletData::KakaoPayRedirect(_) + | api::WalletData::GoPayRedirect(_) + | api::WalletData::GcashRedirect(_) + | api::WalletData::ApplePay(_) + | api::WalletData::ApplePayRedirect(_) + | api::WalletData::ApplePayThirdPartySdk(_) + | api::WalletData::DanaRedirect {} + | api::WalletData::GooglePayRedirect(_) + | api::WalletData::GooglePayThirdPartySdk(_) + | api::WalletData::MbWayRedirect(_) + | api::WalletData::MobilePayRedirect(_) + | api::WalletData::PaypalSdk(_) + | api::WalletData::SamsungPay(_) + | api::WalletData::TwintRedirect {} + | api::WalletData::VippsRedirect {} + | api::WalletData::TouchNGoRedirect(_) + | api::WalletData::WeChatPayRedirect(_) + | api::WalletData::WeChatPayQr(_) + | api::WalletData::CashappQr(_) + | api::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }), api::PaymentMethodData::PayLater( @@ -273,8 +321,17 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques }, ) => Some(Gateway::Klarna), api::PaymentMethodData::MandatePayment => None, - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }; let description = item.get_description()?; @@ -354,8 +411,31 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques }))) } api::WalletData::PaypalRedirect(_) => None, - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), + api::WalletData::AliPayQr(_) + | api::WalletData::AliPayRedirect(_) + | api::WalletData::AliPayHkRedirect(_) + | api::WalletData::MomoRedirect(_) + | api::WalletData::KakaoPayRedirect(_) + | api::WalletData::GoPayRedirect(_) + | api::WalletData::GcashRedirect(_) + | api::WalletData::ApplePay(_) + | api::WalletData::ApplePayRedirect(_) + | api::WalletData::ApplePayThirdPartySdk(_) + | api::WalletData::DanaRedirect {} + | api::WalletData::GooglePayRedirect(_) + | api::WalletData::GooglePayThirdPartySdk(_) + | api::WalletData::MbWayRedirect(_) + | api::WalletData::MobilePayRedirect(_) + | api::WalletData::PaypalSdk(_) + | api::WalletData::SamsungPay(_) + | api::WalletData::TwintRedirect {} + | api::WalletData::VippsRedirect {} + | api::WalletData::TouchNGoRedirect(_) + | api::WalletData::WeChatPayRedirect(_) + | api::WalletData::WeChatPayQr(_) + | api::WalletData::CashappQr(_) + | api::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }, api::PaymentMethodData::PayLater(ref paylater) => { @@ -365,15 +445,36 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for MultisafepayPaymentsReques billing_email, .. } => billing_email.clone(), - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), - ))?, + api_models::payments::PayLaterData::KlarnaSdk { token: _ } + | api_models::payments::PayLaterData::AffirmRedirect {} + | api_models::payments::PayLaterData::AfterpayClearpayRedirect { + billing_email: _, + billing_name: _, + } + | api_models::payments::PayLaterData::PayBrightRedirect {} + | api_models::payments::PayLaterData::WalleyRedirect {} + | api_models::payments::PayLaterData::AlmaRedirect {} + | api_models::payments::PayLaterData::AtomeRedirect {} => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message( + "multisafepay", + ), + ))? + } }), })) } api::PaymentMethodData::MandatePayment => None, - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, };
2023-10-14T13:54:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Removed all the default case handling in multisafepay and handle all the missing cases. Closes: #2274 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
500405d78938772e0e9f8e3ce4f930d782c670fa
juspay/hyperswitch
juspay__hyperswitch-2272
Bug: [REFACTOR]: [Iatapay] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 9d4ecdff197..f98798fe5be 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -86,7 +86,18 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest { let payment_method = item.payment_method; let country = match payment_method { PaymentMethod::Upi => "IN".to_string(), - _ => item.get_billing_country()?.to_string(), + + PaymentMethod::Card + | PaymentMethod::CardRedirect + | PaymentMethod::PayLater + | PaymentMethod::Wallet + | PaymentMethod::BankRedirect + | PaymentMethod::BankTransfer + | PaymentMethod::Crypto + | PaymentMethod::BankDebit + | PaymentMethod::Reward + | PaymentMethod::Voucher + | PaymentMethod::GiftCard => item.get_billing_country()?.to_string(), }; let return_url = item.get_return_url()?; let payer_info = match item.request.payment_method_data.clone() {
2023-10-14T15:42:37Z
## 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 --> - Fix issue https://github.com/juspay/hyperswitch/issues/2272 - Changes to be made : Remove default case handling - Added all the ```ConnectorAuthType``` (which are not ```auth_type``` ) against the default case - File **changed: transformers.rs** (crates/router/src/connector/iatapay/transformers.rs) ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
5d88dbc92ce470c951717debe246e182b3fe5656
juspay/hyperswitch
juspay__hyperswitch-2273
Bug: [REFACTOR]: [Klarna] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 220b8f4a416..1814f9de809 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -288,12 +288,115 @@ impl self.base_url(connectors), token )), - _ => Err(error_stack::report!(errors::ConnectorError::NotSupported { + ( + storage_enums::PaymentExperience::DisplayQrCode + | storage_enums::PaymentExperience::DisplayWaitScreen + | storage_enums::PaymentExperience::InvokePaymentApp + | storage_enums::PaymentExperience::InvokeSdkClient + | storage_enums::PaymentExperience::LinkWallet + | storage_enums::PaymentExperience::OneClick + | storage_enums::PaymentExperience::RedirectToUrl, + api_models::enums::PaymentMethodType::Ach + | api_models::enums::PaymentMethodType::Affirm + | api_models::enums::PaymentMethodType::AfterpayClearpay + | api_models::enums::PaymentMethodType::Alfamart + | api_models::enums::PaymentMethodType::AliPay + | api_models::enums::PaymentMethodType::AliPayHk + | api_models::enums::PaymentMethodType::Alma + | api_models::enums::PaymentMethodType::ApplePay + | api_models::enums::PaymentMethodType::Atome + | api_models::enums::PaymentMethodType::Bacs + | api_models::enums::PaymentMethodType::BancontactCard + | api_models::enums::PaymentMethodType::Becs + | api_models::enums::PaymentMethodType::Benefit + | api_models::enums::PaymentMethodType::Bizum + | api_models::enums::PaymentMethodType::Blik + | api_models::enums::PaymentMethodType::Boleto + | api_models::enums::PaymentMethodType::BcaBankTransfer + | api_models::enums::PaymentMethodType::BniVa + | api_models::enums::PaymentMethodType::BriVa + | api_models::enums::PaymentMethodType::CimbVa + | api_models::enums::PaymentMethodType::ClassicReward + | api_models::enums::PaymentMethodType::Credit + | api_models::enums::PaymentMethodType::CryptoCurrency + | api_models::enums::PaymentMethodType::Cashapp + | api_models::enums::PaymentMethodType::Dana + | api_models::enums::PaymentMethodType::DanamonVa + | api_models::enums::PaymentMethodType::Debit + | api_models::enums::PaymentMethodType::Efecty + | api_models::enums::PaymentMethodType::Eps + | api_models::enums::PaymentMethodType::Evoucher + | api_models::enums::PaymentMethodType::Giropay + | api_models::enums::PaymentMethodType::Givex + | api_models::enums::PaymentMethodType::GooglePay + | api_models::enums::PaymentMethodType::GoPay + | api_models::enums::PaymentMethodType::Gcash + | api_models::enums::PaymentMethodType::Ideal + | api_models::enums::PaymentMethodType::Interac + | api_models::enums::PaymentMethodType::Indomaret + | api_models::enums::PaymentMethodType::Klarna + | api_models::enums::PaymentMethodType::KakaoPay + | api_models::enums::PaymentMethodType::MandiriVa + | api_models::enums::PaymentMethodType::Knet + | api_models::enums::PaymentMethodType::MbWay + | api_models::enums::PaymentMethodType::MobilePay + | api_models::enums::PaymentMethodType::Momo + | api_models::enums::PaymentMethodType::MomoAtm + | api_models::enums::PaymentMethodType::Multibanco + | api_models::enums::PaymentMethodType::OnlineBankingThailand + | api_models::enums::PaymentMethodType::OnlineBankingCzechRepublic + | api_models::enums::PaymentMethodType::OnlineBankingFinland + | api_models::enums::PaymentMethodType::OnlineBankingFpx + | api_models::enums::PaymentMethodType::OnlineBankingPoland + | api_models::enums::PaymentMethodType::OnlineBankingSlovakia + | api_models::enums::PaymentMethodType::Oxxo + | api_models::enums::PaymentMethodType::PagoEfectivo + | api_models::enums::PaymentMethodType::PermataBankTransfer + | api_models::enums::PaymentMethodType::OpenBankingUk + | api_models::enums::PaymentMethodType::PayBright + | api_models::enums::PaymentMethodType::Paypal + | api_models::enums::PaymentMethodType::Pix + | api_models::enums::PaymentMethodType::PaySafeCard + | api_models::enums::PaymentMethodType::Przelewy24 + | api_models::enums::PaymentMethodType::Pse + | api_models::enums::PaymentMethodType::RedCompra + | api_models::enums::PaymentMethodType::RedPagos + | api_models::enums::PaymentMethodType::SamsungPay + | api_models::enums::PaymentMethodType::Sepa + | api_models::enums::PaymentMethodType::Sofort + | api_models::enums::PaymentMethodType::Swish + | api_models::enums::PaymentMethodType::TouchNGo + | api_models::enums::PaymentMethodType::Trustly + | api_models::enums::PaymentMethodType::Twint + | api_models::enums::PaymentMethodType::UpiCollect + | api_models::enums::PaymentMethodType::Vipps + | api_models::enums::PaymentMethodType::Walley + | api_models::enums::PaymentMethodType::WeChatPay + | api_models::enums::PaymentMethodType::SevenEleven + | api_models::enums::PaymentMethodType::Lawson + | api_models::enums::PaymentMethodType::MiniStop + | api_models::enums::PaymentMethodType::FamilyMart + | api_models::enums::PaymentMethodType::Seicomart + | api_models::enums::PaymentMethodType::PayEasy, + ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { message: payment_method_type.to_string(), connector: "klarna", })), }, - _ => Err(error_stack::report!( + + api_payments::PaymentMethodData::Card(_) + | api_payments::PaymentMethodData::CardRedirect(_) + | api_payments::PaymentMethodData::Wallet(_) + | api_payments::PaymentMethodData::PayLater(_) + | api_payments::PaymentMethodData::BankRedirect(_) + | api_payments::PaymentMethodData::BankDebit(_) + | api_payments::PaymentMethodData::BankTransfer(_) + | api_payments::PaymentMethodData::Crypto(_) + | api_payments::PaymentMethodData::MandatePayment + | api_payments::PaymentMethodData::Reward + | api_payments::PaymentMethodData::Upi(_) + | api_payments::PaymentMethodData::Voucher(_) + | api_payments::PaymentMethodData::GiftCard(_) => Err(error_stack::report!( errors::ConnectorError::MismatchedPaymentData )), }
2023-10-01T10:51:34Z
## Type of Change - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Match arms using the wildcard patten (`_`) can be dangereous when extending enums since developers may miss locations where new variants should be handled. This patch expands all wildcard patterns in the Klarna connector to avoid this problem. ## Motivation and Context Fixes #2273 ## How did you test it? `cargo check`, `cargo clippy`, and `cargo test` all pass without errors in modified files. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
c81d8e9a180da8f71d156d39c9f85847f6d7a572
juspay/hyperswitch
juspay__hyperswitch-2270
Bug: [REFACTOR]: [Forte] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index bc7c55c4f87..7851608d11b 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -101,9 +101,23 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { card, }) } - _ => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - ))?, + api_models::payments::PaymentMethodData::CardRedirect(_) + | api_models::payments::PaymentMethodData::Wallet(_) + | api_models::payments::PaymentMethodData::PayLater(_) + | api_models::payments::PaymentMethodData::BankRedirect(_) + | api_models::payments::PaymentMethodData::BankDebit(_) + | api_models::payments::PaymentMethodData::BankTransfer(_) + | api_models::payments::PaymentMethodData::Crypto(_) + | api_models::payments::PaymentMethodData::MandatePayment {} + | api_models::payments::PaymentMethodData::Reward {} + | api_models::payments::PaymentMethodData::Upi(_) + | api_models::payments::PaymentMethodData::Voucher(_) + | api_models::payments::PaymentMethodData::GiftCard(_) => { + Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Forte", + })? + } } } }
2023-10-18T08:56:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Addresses Issue #2270 - Modified `crates/router/src/connector/forte/transformers.rs` - Convert `NotImplemented` to `NotSupported` in default case ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
6cf8f0582cfa4f6a58c67a868cb67846970b3835
juspay/hyperswitch
juspay__hyperswitch-2268
Bug: [REFACTOR]: [Cybersource] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 9b0bf61c545..324fe77d0bc 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -193,9 +193,22 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { utils::get_unimplemented_payment_method_error_message("Cybersource"), ))?, }, - _ => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Cybersource"), - ))?, + payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + ))? + } }; let processing_information = ProcessingInformation {
2023-10-26T21:29:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/2268 ## 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)? --> Make a mandate payment for cybersource, for the payment method which is not implemented like bank_debit or bank_transfer and check for the error message - it should be PM not implemented ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
a8c74321dbba5c7be6468fff7680d703d726a781
juspay/hyperswitch
juspay__hyperswitch-2269
Bug: [REFACTOR]: [Dlocal] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 8558836372e..18a6ad46755 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -118,7 +118,20 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for DlocalPaymentsRequest { }; Ok(payment_request) } - _ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()), + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::Wallet(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + crate::connector::utils::get_unimplemented_payment_method_error_message("Dlocal"), + ))?, } } }
2023-10-18T08:01:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description removed all the default case in dlocal and handle all the missing cases closes #2269 ### 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` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
a1472c6b78afa819cbe026a7db1e0c2b9016715e
juspay/hyperswitch
juspay__hyperswitch-2250
Bug: [FEATURE]: [Worldpay] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index 0c69cd981bb..60a5fc83045 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -56,6 +56,10 @@ impl ConnectorCommon for Worldpay { "worldpay" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + fn common_get_content_type(&self) -> &'static str { "application/vnd.worldpay.payments-v6+json" } @@ -428,7 +432,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_request = WorldpayPaymentsRequest::try_from(req)?; + let connector_router_data = worldpay::WorldpayRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_request = WorldpayPaymentsRequest::try_from(&connector_router_data)?; let worldpay_payment_request = types::RequestBody::log_and_get_request_body( &connector_request, ext_traits::Encode::<WorldpayPaymentsRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 3d467f4198f..aabe27fc4eb 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -3,15 +3,44 @@ use common_utils::errors::CustomResult; use diesel_models::enums; use error_stack::{IntoReport, ResultExt}; use masking::{PeekInterface, Secret}; +use serde::Serialize; use super::{requests::*, response::*}; use crate::{ connector::utils, consts, core::errors, - types::{self, api}, + types::{self, api, PaymentsAuthorizeData, PaymentsResponseData}, }; +#[derive(Debug, Serialize)] +pub struct WorldpayRouterData<T> { + amount: i64, + router_data: T, +} +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for WorldpayRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (_currency_unit, _currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + amount, + router_data: item, + }) + } +} fn fetch_payment_instrument( payment_method: api::PaymentMethodData, ) -> CustomResult<PaymentInstrument, errors::ConnectorError> { @@ -100,29 +129,48 @@ fn fetch_payment_instrument( } } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for WorldpayPaymentsRequest { +impl + TryFrom< + &WorldpayRouterData< + &types::RouterData< + types::api::payments::Authorize, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + >, + > for WorldpayPaymentsRequest +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + + fn try_from( + item: &WorldpayRouterData< + &types::RouterData< + types::api::payments::Authorize, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + >, + ) -> Result<Self, Self::Error> { Ok(Self { instruction: Instruction { value: PaymentValue { - amount: item.request.amount, - currency: item.request.currency.to_string(), + amount: item.amount, + currency: item.router_data.request.currency.to_string(), }, narrative: InstructionNarrative { - line1: item.merchant_id.clone().replace('_', "-"), + line1: item.router_data.merchant_id.clone().replace('_', "-"), ..Default::default() }, payment_instrument: fetch_payment_instrument( - item.request.payment_method_data.clone(), + item.router_data.request.payment_method_data.clone(), )?, debt_repayment: None, }, merchant: Merchant { - entity: item.attempt_id.clone().replace('_', "-"), + entity: item.router_data.attempt_id.clone().replace('_', "-"), ..Default::default() }, - transaction_reference: item.attempt_id.clone(), + transaction_reference: item.router_data.attempt_id.clone(), channel: None, customer: None, }) diff --git a/package.json b/package.json index 0766efdcc17..45d2be3153b 100644 --- a/package.json +++ b/package.json @@ -6,4 +6,4 @@ "devDependencies": { "newman": "git+ssh://git@github.com:knutties/newman.git#7106e194c15d49d066fa09d9a2f18b2238f3dba8" } -} +} \ No newline at end of file
2023-10-03T16:27: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 pull request implements the get_currency_unit from the ConnectorCommon trait for the Worldpay connector. This function allows connectors to declare their accepted currency unit as either Base or Minor. For Worldpay it accepts currency as Minor units. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ### Links to the files with corresponding changes. 1. crates\router\src\connector\worldpay.rs 2. crates\router\src\connector\worldpay\transformers.rs ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with 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 #2250. ## How did you test it? I tried setting up and testing using VS code and codesandbox but was not able to do it. So kindly review the changes and do let me know if any further issues. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
b5b3625efdd70c619e9fc206721c4bedf8af30a4
juspay/hyperswitch
juspay__hyperswitch-2267
Bug: [REFACTOR]: [CryptoPay] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index a49380cb365..8d9f277dd0f 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -69,9 +69,23 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> custom_id: item.router_data.connector_request_reference_id.clone(), }) } - _ => Err(errors::ConnectorError::NotImplemented( - "payment method".to_string(), - )), + api_models::payments::PaymentMethodData::Card(_) + | api_models::payments::PaymentMethodData::CardRedirect(_) + | api_models::payments::PaymentMethodData::Wallet(_) + | api_models::payments::PaymentMethodData::PayLater(_) + | api_models::payments::PaymentMethodData::BankRedirect(_) + | api_models::payments::PaymentMethodData::BankDebit(_) + | api_models::payments::PaymentMethodData::BankTransfer(_) + | api_models::payments::PaymentMethodData::MandatePayment {} + | api_models::payments::PaymentMethodData::Reward {} + | api_models::payments::PaymentMethodData::Upi(_) + | api_models::payments::PaymentMethodData::Voucher(_) + | api_models::payments::PaymentMethodData::GiftCard(_) => { + Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "CryptoPay", + }) + } }?; Ok(cryptopay_request) }
2023-10-19T10:21:04Z
## 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 --> Removed the default match case as mentioned in the issue ### 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
664093dc79743203196d912c17570885718b1c02
juspay/hyperswitch
juspay__hyperswitch-2262
Bug: [REFACTOR]: [Airwallex] Remove Default Case Handling ### :memo: Feature Description - We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector. - These conditions generally go hand in hand with enum variants. - Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered. - So, if all the explicit cases are handled then default is used to handle the rest. - Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases. - This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases. ### :hammer: Possible Implementation - Instead of relying on a default match case `_`, developers should handle each and every variant explicitly. - By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 51258643c64..031a8276bb0 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -186,8 +186,18 @@ impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>> })) } api::PaymentMethodData::Wallet(ref wallet_data) => get_wallet_details(wallet_data), - _ => Err(errors::ConnectorError::NotImplemented( - "Unknown payment method".to_string(), + api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("airwallex"), )), }?; @@ -215,9 +225,35 @@ fn get_wallet_details( payment_method_type: AirwallexPaymentType::Googlepay, })) } - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), - ))?, + api_models::payments::WalletData::AliPayQr(_) + | api_models::payments::WalletData::AliPayRedirect(_) + | api_models::payments::WalletData::AliPayHkRedirect(_) + | api_models::payments::WalletData::MomoRedirect(_) + | api_models::payments::WalletData::KakaoPayRedirect(_) + | api_models::payments::WalletData::GoPayRedirect(_) + | api_models::payments::WalletData::GcashRedirect(_) + | api_models::payments::WalletData::ApplePay(_) + | api_models::payments::WalletData::ApplePayRedirect(_) + | api_models::payments::WalletData::ApplePayThirdPartySdk(_) + | api_models::payments::WalletData::DanaRedirect {} + | api_models::payments::WalletData::GooglePayRedirect(_) + | api_models::payments::WalletData::GooglePayThirdPartySdk(_) + | api_models::payments::WalletData::MbWayRedirect(_) + | api_models::payments::WalletData::MobilePayRedirect(_) + | api_models::payments::WalletData::PaypalRedirect(_) + | api_models::payments::WalletData::PaypalSdk(_) + | api_models::payments::WalletData::SamsungPay(_) + | api_models::payments::WalletData::TwintRedirect {} + | api_models::payments::WalletData::VippsRedirect {} + | api_models::payments::WalletData::TouchNGoRedirect(_) + | api_models::payments::WalletData::WeChatPayRedirect(_) + | api_models::payments::WalletData::WeChatPayQr(_) + | api_models::payments::WalletData::CashappQr(_) + | api_models::payments::WalletData::SwishQr(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("airwallex"), + ))? + } }; Ok(wallet_details) }
2023-10-26T18:19:54Z
## 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 --> #2262 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? No test cases. As In this PR only error message have been populated for all default cases. <!-- 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
6dc71fe9923a793b76eee2ea1ac1060ab584a303
juspay/hyperswitch
juspay__hyperswitch-2248
Bug: [FEATURE]: [Tsys] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/tsys.rs b/crates/router/src/connector/tsys.rs index 869aa535636..e7e818062e2 100644 --- a/crates/router/src/connector/tsys.rs +++ b/crates/router/src/connector/tsys.rs @@ -71,6 +71,10 @@ impl ConnectorCommon for Tsys { "tsys" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -227,7 +231,16 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe &self, req: &types::PaymentsSyncRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = tsys::TsysSyncRequest::try_from(req)?; + + let connector_router_data = tsys::TsysRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + + let req_obj = tsys::TsysPaymentsRequest::try_from(&connector_router_data)?; + let tsys_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<tsys::TsysSyncRequest>::encode_to_string_of_json, @@ -461,7 +474,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = tsys::TsysRefundRequest::try_from(req)?; + let connector_router_data = tsys::TsysRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let req_obj = tsys::TsysRefundRequest::try_from(&connector_router_data)?; let tsys_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<tsys::TsysRefundRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs index a3bd1c4a074..857e5c06460 100644 --- a/crates/router/src/connector/tsys/transformers.rs +++ b/crates/router/src/connector/tsys/transformers.rs @@ -17,7 +17,37 @@ pub enum TsysPaymentsRequest { Sale(TsysPaymentAuthSaleRequest), } -#[derive(Default, Debug, Serialize)] +#[derive(Debug, Serialize)] +pub struct TsysRouterData<T> { + pub amount: String, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for TsysRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (currency_unit, currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data: item, + }) + } +} + #[serde(rename_all = "camelCase")] pub struct TsysPaymentAuthSaleRequest { #[serde(rename = "deviceID")] @@ -37,9 +67,11 @@ pub struct TsysPaymentAuthSaleRequest { order_number: String, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest { +impl TryFrom<&TsysRouterData<&types::PaymentsAuthorizeRouterData>> for TsysPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + fn try_from( + item: &TsysRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(ccard) => { let connector_auth: TsysAuthType = @@ -459,9 +491,9 @@ pub struct TsysRefundRequest { return_request: TsysReturnRequest, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for TsysRefundRequest { +impl<F> TryFrom<&TsysRouterData::RefundsRouterData<F>> for TsysRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &TsysRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?; let return_request = TsysReturnRequest { device_id: connector_auth.device_id,
2023-10-31T16:54:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - This PR is related with #2248 which implements `get_currency_unit` fn. , `TsysRouterData<T>` struct and functionality ### 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)? --> Got to test it by paying using Tsys and test the currency unit. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8e484ddab8d3f4463299c7f7e8ce75b8dd628599
juspay/hyperswitch
juspay__hyperswitch-2249
Bug: [FEATURE]: [Worldline] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs index 4e69fd5ca0a..b10e3dcd74c 100644 --- a/crates/router/src/connector/worldline.rs +++ b/crates/router/src/connector/worldline.rs @@ -112,6 +112,10 @@ impl ConnectorCommon for Worldline { "worldline" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.worldline.base_url.as_ref() } @@ -486,7 +490,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = worldline::PaymentsRequest::try_from(req)?; + let connector_router_data = worldline::WorldlineRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = worldline::PaymentsRequest::try_from(&connector_router_data)?; let worldline_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<worldline::PaymentsRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index d02ab60c8b9..f11c2398080 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -13,6 +13,7 @@ use crate::{ api::{self, enums as api_enums}, storage::enums, transformers::ForeignFrom, + PaymentsAuthorizeData, PaymentsResponseData, }, }; @@ -183,38 +184,91 @@ pub struct PaymentsRequest { pub shipping: Option<Shipping>, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest { +#[derive(Debug, Serialize)] +pub struct WorldlineRouterData<T> { + amount: i64, + router_data: T, +} +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for WorldlineRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (_currency_unit, _currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + amount, + router_data: item, + }) + } +} + +impl + TryFrom< + &WorldlineRouterData< + &types::RouterData< + types::api::payments::Authorize, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + >, + > for PaymentsRequest +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let payment_data = match item.request.payment_method_data { - api::PaymentMethodData::Card(ref card) => { + + fn try_from( + item: &WorldlineRouterData< + &types::RouterData< + types::api::payments::Authorize, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + >, + ) -> Result<Self, Self::Error> { + let payment_data = match &item.router_data.request.payment_method_data { + api::PaymentMethodData::Card(card) => { WorldlinePaymentMethod::CardPaymentMethodSpecificInput(Box::new(make_card_request( - &item.request, + &item.router_data.request, card, )?)) } - api::PaymentMethodData::BankRedirect(ref bank_redirect) => { + api::PaymentMethodData::BankRedirect(bank_redirect) => { WorldlinePaymentMethod::RedirectPaymentMethodSpecificInput(Box::new( - make_bank_redirect_request(&item.request, bank_redirect)?, + make_bank_redirect_request(&item.router_data.request, bank_redirect)?, )) } - _ => Err(errors::ConnectorError::NotImplemented( - "Payment methods".to_string(), - ))?, + _ => { + return Err( + errors::ConnectorError::NotImplemented("Payment methods".to_string()).into(), + ) + } }; - let customer = build_customer_info(&item.address, &item.request.email)?; + + let customer = + build_customer_info(&item.router_data.address, &item.router_data.request.email)?; let order = Order { amount_of_money: AmountOfMoney { - amount: item.request.amount, - currency_code: item.request.currency.to_string().to_uppercase(), + amount: item.amount, + currency_code: item.router_data.request.currency.to_string().to_uppercase(), }, customer, references: References { - merchant_reference: item.connector_request_reference_id.clone(), + merchant_reference: item.router_data.connector_request_reference_id.clone(), }, }; let shipping = item + .router_data .address .shipping .as_ref() @@ -227,6 +281,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentsRequest { }) } } + #[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)] pub enum Gateway { Amex = 2, @@ -276,7 +331,7 @@ impl TryFrom<&api_models::enums::BankNames> for WorldlineBic { } fn make_card_request( - req: &types::PaymentsAuthorizeData, + req: &PaymentsAuthorizeData, ccard: &payments::Card, ) -> Result<CardPaymentMethod, error_stack::Report<errors::ConnectorError>> { let expiry_year = ccard.card_exp_year.peek().clone(); @@ -303,7 +358,7 @@ fn make_card_request( } fn make_bank_redirect_request( - req: &types::PaymentsAuthorizeData, + req: &PaymentsAuthorizeData, bank_redirect: &payments::BankRedirectData, ) -> Result<RedirectPaymentMethod, error_stack::Report<errors::ConnectorError>> { let return_url = req.router_return_url.clone(); @@ -497,12 +552,12 @@ pub struct Payment { pub capture_method: enums::CaptureMethod, } -impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, PaymentsResponseData>> + for types::RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, Payment, T, types::PaymentsResponseData>, + item: types::ResponseRouterData<F, Payment, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::foreign_from(( @@ -541,12 +596,12 @@ pub struct RedirectData { pub redirect_url: Url, } -impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>> + for types::RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, PaymentResponse, T, types::PaymentsResponseData>, + item: types::ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirection_data = item .response
2023-10-12T18:04:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This pull request implements the get_currency_unit from the ConnectorCommon trait for the Worldline connector. This function allows connectors to declare their accepted currency unit as either Base or Minor. For Worldline it accepts currency as Minor units. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Links to the files with corresponding changes. 1. crates/router/src/connector/worldline.rs 2. crates/router/src/connector/worldline/transformers.rs ## Motivation and Context Closes #2249 ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
1afae7e69a81afeff3a7ff55f2b2d5b063afb7c1
juspay/hyperswitch
juspay__hyperswitch-2244
Bug: [FEATURE]: [Rapyd] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs index 292e6c55f26..29f21f37381 100644 --- a/crates/router/src/connector/rapyd.rs +++ b/crates/router/src/connector/rapyd.rs @@ -64,6 +64,10 @@ impl ConnectorCommon for Rapyd { "rapyd" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -179,7 +183,13 @@ impl &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = rapyd::RapydPaymentsRequest::try_from(req)?; + let connector_router_data = rapyd::RapydRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let req_obj = rapyd::RapydPaymentsRequest::try_from(&connector_router_data)?; let rapyd_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<rapyd::RapydPaymentsRequest>::encode_to_string_of_json, @@ -483,7 +493,13 @@ impl &self, req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = rapyd::CaptureRequest::try_from(req)?; + let connector_router_data = rapyd::RapydRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount_to_capture, + req, + ))?; + let req_obj = rapyd::CaptureRequest::try_from(&connector_router_data)?; let rapyd_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<rapyd::CaptureRequest>::encode_to_string_of_json, @@ -615,7 +631,13 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = rapyd::RapydRefundRequest::try_from(req)?; + let connector_router_data = rapyd::RapydRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let req_obj = rapyd::RapydRefundRequest::try_from(&connector_router_data)?; let rapyd_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<rapyd::RapydRefundRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 79ad6838ac3..9df699b938b 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -13,6 +13,36 @@ use crate::{ utils::OptionExt, }; +#[derive(Debug, Serialize)] +pub struct RapydRouterData<T> { + pub amount: i64, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for RapydRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (_currency_unit, _currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + amount, + router_data: item, + }) + } +} + #[derive(Default, Debug, Serialize)] pub struct RapydPaymentsRequest { pub amount: i64, @@ -69,18 +99,23 @@ pub struct RapydWallet { token: Option<String>, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest { +impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let (capture, payment_method_options) = match item.payment_method { + fn try_from( + item: &RapydRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let (capture, payment_method_options) = match item.router_data.payment_method { diesel_models::enums::PaymentMethod::Card => { - let three_ds_enabled = matches!(item.auth_type, enums::AuthenticationType::ThreeDs); + let three_ds_enabled = matches!( + item.router_data.auth_type, + enums::AuthenticationType::ThreeDs + ); let payment_method_options = PaymentMethodOptions { three_ds: three_ds_enabled, }; ( Some(matches!( - item.request.capture_method, + item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None )), Some(payment_method_options), @@ -88,7 +123,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest { } _ => (None, None), }; - let payment_method = match item.request.payment_method_data { + let payment_method = match item.router_data.request.payment_method_data { api_models::payments::PaymentMethodData::Card(ref ccard) => { Some(PaymentMethod { pm_type: "in_amex_card".to_owned(), //[#369] Map payment method type based on country @@ -128,10 +163,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for RapydPaymentsRequest { .change_context(errors::ConnectorError::NotImplemented( "payment_method".to_owned(), ))?; - let return_url = item.request.get_return_url()?; + let return_url = item.router_data.request.get_return_url()?; Ok(Self { - amount: item.request.amount, - currency: item.request.currency, + amount: item.amount, + currency: item.router_data.request.currency, payment_method, capture, payment_method_options, @@ -276,13 +311,17 @@ pub struct RapydRefundRequest { pub currency: Option<enums::Currency>, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for RapydRefundRequest { +impl<F> TryFrom<&RapydRouterData<&types::RefundsRouterData<F>>> for RapydRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &RapydRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { - payment: item.request.connector_transaction_id.to_string(), - amount: Some(item.request.refund_amount), - currency: Some(item.request.currency), + payment: item + .router_data + .request + .connector_transaction_id + .to_string(), + amount: Some(item.amount), + currency: Some(item.router_data.request.currency), }) } } @@ -380,11 +419,13 @@ pub struct CaptureRequest { statement_descriptor: Option<String>, } -impl TryFrom<&types::PaymentsCaptureRouterData> for CaptureRequest { +impl TryFrom<&RapydRouterData<&types::PaymentsCaptureRouterData>> for CaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + fn try_from( + item: &RapydRouterData<&types::PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { Ok(Self { - amount: Some(item.request.amount_to_capture), + amount: Some(item.amount), receipt_email: None, statement_descriptor: None, })
2023-10-22T19:22:53Z
## 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 solves issue number #2244 for currency unit conversion in Rapyd 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). --> Closes #2244. ## How did you test it? Create a payment via hyperswitch, (Rapyd connector) and match the amount you are passing in your request with amount you are getting in connector response. Both should be same ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
af90089010e06ed45a70c51d4143260eec45b6dc
juspay/hyperswitch
juspay__hyperswitch-2246
Bug: [FEATURE]: [Stax] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/stax.rs b/crates/router/src/connector/stax.rs index 82a4c7ff323..7f5fde71938 100644 --- a/crates/router/src/connector/stax.rs +++ b/crates/router/src/connector/stax.rs @@ -70,6 +70,10 @@ impl ConnectorCommon for Stax { "stax" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -347,7 +351,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = stax::StaxPaymentsRequest::try_from(req)?; + let connector_router_data = stax::StaxRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let req_obj = stax::StaxPaymentsRequest::try_from(&connector_router_data)?; let stax_req = types::RequestBody::log_and_get_request_body( &req_obj, @@ -503,7 +513,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme &self, req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = stax::StaxCaptureRequest::try_from(req)?; + let connector_router_data = stax::StaxRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount_to_capture, + req, + ))?; + let connector_req = stax::StaxCaptureRequest::try_from(&connector_router_data)?; let stax_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<stax::StaxCaptureRequest>::encode_to_string_of_json, @@ -657,7 +673,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = stax::StaxRefundRequest::try_from(req)?; + let connector_router_data = stax::StaxRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let req_obj = stax::StaxRefundRequest::try_from(&connector_router_data)?; let stax_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<stax::StaxRefundRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 4ee28be1937..f2aae442ddd 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -11,6 +11,37 @@ use crate::{ types::{self, api, storage::enums}, }; +#[derive(Debug, Serialize)] +pub struct StaxRouterData<T> { + pub amount: f64, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for StaxRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (currency_unit, currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data: item, + }) + } +} + #[derive(Debug, Serialize)] pub struct StaxPaymentsRequestMetaData { tax: i64, @@ -26,21 +57,23 @@ pub struct StaxPaymentsRequest { idempotency_id: Option<String>, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { +impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - if item.request.currency != enums::Currency::USD { + fn try_from( + item: &StaxRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + if item.router_data.request.currency != enums::Currency::USD { Err(errors::ConnectorError::NotSupported { - message: item.request.currency.to_string(), + message: item.router_data.request.currency.to_string(), connector: "Stax", })? } - let total = utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?; + let total = item.amount; - match item.request.payment_method_data.clone() { + match item.router_data.request.payment_method_data.clone() { api::PaymentMethodData::Card(_) => { - let pm_token = item.get_payment_method_token()?; - let pre_auth = !item.request.is_auto_capture()?; + let pm_token = item.router_data.get_payment_method_token()?; + let pre_auth = !item.router_data.request.is_auto_capture()?; Ok(Self { meta: StaxPaymentsRequestMetaData { tax: 0 }, total, @@ -52,14 +85,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { Err(errors::ConnectorError::InvalidWalletToken)? } }), - idempotency_id: Some(item.connector_request_reference_id.clone()), + idempotency_id: Some(item.router_data.connector_request_reference_id.clone()), }) } api::PaymentMethodData::BankDebit( api_models::payments::BankDebitData::AchBankDebit { .. }, ) => { - let pm_token = item.get_payment_method_token()?; - let pre_auth = !item.request.is_auto_capture()?; + let pm_token = item.router_data.get_payment_method_token()?; + let pre_auth = !item.router_data.request.is_auto_capture()?; Ok(Self { meta: StaxPaymentsRequestMetaData { tax: 0 }, total, @@ -71,7 +104,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for StaxPaymentsRequest { Err(errors::ConnectorError::InvalidWalletToken)? } }), - idempotency_id: Some(item.connector_request_reference_id.clone()), + idempotency_id: Some(item.router_data.connector_request_reference_id.clone()), }) } api::PaymentMethodData::BankDebit(_) @@ -347,13 +380,12 @@ pub struct StaxCaptureRequest { total: Option<f64>, } -impl TryFrom<&types::PaymentsCaptureRouterData> for StaxCaptureRequest { +impl TryFrom<&StaxRouterData<&types::PaymentsCaptureRouterData>> for StaxCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { - let total = utils::to_currency_base_unit_asf64( - item.request.amount_to_capture, - item.request.currency, - )?; + fn try_from( + item: &StaxRouterData<&types::PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { + let total = item.amount; Ok(Self { total: Some(total) }) } } @@ -365,15 +397,10 @@ pub struct StaxRefundRequest { pub total: f64, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for StaxRefundRequest { +impl<F> TryFrom<&StaxRouterData<&types::RefundsRouterData<F>>> for StaxRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { - Ok(Self { - total: utils::to_currency_base_unit_asf64( - item.request.refund_amount, - item.request.currency, - )?, - }) + fn try_from(item: &StaxRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { total: item.amount }) } }
2023-10-27T14:45:03Z
## 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 solves the Currency Unit Conversion for STAX Connector and fixes issue #2246 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> We need to create a payment using Stax and test the currency unit from connector response and connector 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` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
e40a29351c7aa7b86a5684959a84f0236104cafd
juspay/hyperswitch
juspay__hyperswitch-2241
Bug: [FEATURE]: [Payeezy] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/payeezy.rs b/crates/router/src/connector/payeezy.rs index da712605437..03e76af907c 100644 --- a/crates/router/src/connector/payeezy.rs +++ b/crates/router/src/connector/payeezy.rs @@ -90,6 +90,10 @@ impl ConnectorCommon for Payeezy { "payeezy" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -292,12 +296,19 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme &self, req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = payeezy::PayeezyCaptureOrVoidRequest::try_from(req)?; + let router_obj = payeezy::PayeezyRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount_to_capture, + req, + ))?; + let req_obj = payeezy::PayeezyCaptureOrVoidRequest::try_from(&router_obj)?; let payeezy_req = types::RequestBody::log_and_get_request_body( - &connector_req, + &req_obj, utils::Encode::<payeezy::PayeezyCaptureOrVoidRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(payeezy_req)) } @@ -380,9 +391,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = payeezy::PayeezyPaymentsRequest::try_from(req)?; + let router_obj = payeezy::PayeezyRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let req_obj = payeezy::PayeezyPaymentsRequest::try_from(&router_obj)?; + let payeezy_req = types::RequestBody::log_and_get_request_body( - &connector_req, + &req_obj, utils::Encode::<payeezy::PayeezyPaymentsRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; @@ -469,10 +487,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = payeezy::PayeezyRefundRequest::try_from(req)?; + let router_obj = payeezy::PayeezyRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let req_obj = payeezy::PayeezyRefundRequest::try_from(&router_obj)?; let payeezy_req = types::RequestBody::log_and_get_request_body( - &connector_req, - utils::Encode::<payeezy::PayeezyCaptureOrVoidRequest>::encode_to_string_of_json, + &req_obj, + utils::Encode::<payeezy::PayeezyRefundRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(payeezy_req)) @@ -499,16 +523,22 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon data: &types::RefundsRouterData<api::Execute>, res: Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + // Parse the response into a payeezy::RefundResponse let response: payeezy::RefundResponse = res .response .parse_struct("payeezy RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - types::RefundsRouterData::try_from(types::ResponseRouterData { + + // Create a new instance of types::RefundsRouterData based on the response, input data, and HTTP code + let response_data = types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, - }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + }; + let router_data = types::RefundsRouterData::try_from(response_data) + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + + Ok(router_data) } fn get_error_response( diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index efcd1b36d5b..3a859b32530 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -9,6 +9,37 @@ use crate::{ core::errors, types::{self, api, storage::enums, transformers::ForeignFrom}, }; +#[derive(Debug, Serialize)] +pub struct PayeezyRouterData<T> { + pub amount: String, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for PayeezyRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (currency_unit, currency, amount, router_data): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data, + }) + } +} #[derive(Serialize, Debug)] pub struct PayeezyCard { @@ -66,7 +97,7 @@ pub struct PayeezyPaymentsRequest { pub merchant_ref: String, pub transaction_type: PayeezyTransactionType, pub method: PayeezyPaymentMethodType, - pub amount: i64, + pub amount: String, pub currency_code: String, pub credit_card: PayeezyPaymentMethod, pub stored_credentials: Option<StoredCredentials>, @@ -95,10 +126,12 @@ pub enum Initiator { CardHolder, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayeezyPaymentsRequest { +impl TryFrom<&PayeezyRouterData<&types::PaymentsAuthorizeRouterData>> for PayeezyPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match item.payment_method { + fn try_from( + item: &PayeezyRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.payment_method { diesel_models::enums::PaymentMethod::Card => get_card_specific_payment_data(item), diesel_models::enums::PaymentMethod::CardRedirect @@ -119,14 +152,15 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayeezyPaymentsRequest { } fn get_card_specific_payment_data( - item: &types::PaymentsAuthorizeRouterData, + item: &PayeezyRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<PayeezyPaymentsRequest, error_stack::Report<errors::ConnectorError>> { - let merchant_ref = item.attempt_id.to_string(); + let merchant_ref = item.router_data.attempt_id.to_string(); let method = PayeezyPaymentMethodType::CreditCard; - let amount = item.request.amount; - let currency_code = item.request.currency.to_string(); + let amount = item.amount.clone(); + let currency_code = item.router_data.request.currency.to_string(); let credit_card = get_payment_method_data(item)?; - let (transaction_type, stored_credentials) = get_transaction_type_and_stored_creds(item)?; + let (transaction_type, stored_credentials) = + get_transaction_type_and_stored_creds(item.router_data)?; Ok(PayeezyPaymentsRequest { merchant_ref, transaction_type, @@ -135,7 +169,7 @@ fn get_card_specific_payment_data( currency_code, credit_card, stored_credentials, - reference: item.connector_request_reference_id.clone(), + reference: item.router_data.connector_request_reference_id.clone(), }) } fn get_transaction_type_and_stored_creds( @@ -201,9 +235,9 @@ fn is_mandate_payment( } fn get_payment_method_data( - item: &types::PaymentsAuthorizeRouterData, + item: &PayeezyRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<PayeezyPaymentMethod, error_stack::Report<errors::ConnectorError>> { - match item.request.payment_method_data { + match item.router_data.request.payment_method_data { api::PaymentMethodData::Card(ref card) => { let card_type = PayeezyCardType::try_from(card.get_card_issuer()?)?; let payeezy_card = PayeezyCard { @@ -305,16 +339,20 @@ pub struct PayeezyCaptureOrVoidRequest { currency_code: String, } -impl TryFrom<&types::PaymentsCaptureRouterData> for PayeezyCaptureOrVoidRequest { +impl TryFrom<&PayeezyRouterData<&types::PaymentsCaptureRouterData>> + for PayeezyCaptureOrVoidRequest +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + fn try_from( + item: &PayeezyRouterData<&types::PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { let metadata: PayeezyPaymentsMetadata = - utils::to_connector_meta(item.request.connector_meta.clone()) + utils::to_connector_meta(item.router_data.request.connector_meta.clone()) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Self { transaction_type: PayeezyTransactionType::Capture, - amount: item.request.amount_to_capture.to_string(), - currency_code: item.request.currency.to_string(), + amount: item.amount.clone(), + currency_code: item.router_data.request.currency.to_string(), transaction_tag: metadata.transaction_tag, }) } @@ -338,6 +376,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for PayeezyCaptureOrVoidRequest { }) } } + #[derive(Debug, Deserialize, Serialize, Default)] #[serde(rename_all = "lowercase")] pub enum PayeezyTransactionType { @@ -442,16 +481,18 @@ pub struct PayeezyRefundRequest { currency_code: String, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for PayeezyRefundRequest { +impl<F> TryFrom<&PayeezyRouterData<&types::RefundsRouterData<F>>> for PayeezyRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from( + item: &PayeezyRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { let metadata: PayeezyPaymentsMetadata = - utils::to_connector_meta(item.request.connector_metadata.clone()) + utils::to_connector_meta(item.router_data.request.connector_metadata.clone()) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Self { transaction_type: PayeezyTransactionType::Refund, - amount: item.request.refund_amount.to_string(), - currency_code: item.request.currency.to_string(), + amount: item.amount.clone(), + currency_code: item.router_data.request.currency.to_string(), transaction_tag: metadata.transaction_tag, }) }
2023-10-27T13:51:28Z
## 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 --> ### 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` --> Modified two files in `hyperswitch/crates/router/src/connector/` - Addressing Issue #2241 - `payeezy.rs` - Implement `get_currency_unit` function - Modify `ConnectorIntegration` implementations for `Payeezy` - `payeezy/transformers.rs` - Implement `PayeezyRouterData<T>` structure and functionality - Modify implementation for `PayeezyPaymentsRequest` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with 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 #2241 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> We need to create a payment using payeezy and test the currency unit from connector response and connector dashboard. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
cdca284b2a7a77cb22074fa8b3b380a088c10f00
juspay/hyperswitch
juspay__hyperswitch-2237
Bug: [FEATURE]: [Noon] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs index 45792864255..3bfcbbc6169 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -114,6 +114,10 @@ impl ConnectorCommon for Noon { "noon" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -213,7 +217,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = noon::NoonPaymentsRequest::try_from(req)?; + let router_obj = noon::NoonRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let req_obj = noon::NoonPaymentsRequest::try_from(&router_obj)?; let noon_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<noon::NoonPaymentsRequest>::encode_to_string_of_json, @@ -519,7 +529,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = noon::NoonPaymentsActionRequest::try_from(req)?; + let router_obj = noon::NoonRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let req_obj = noon::NoonPaymentsActionRequest::try_from(&router_obj)?; let noon_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<noon::NoonPaymentsActionRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 5ff92582051..d6b46d9743d 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -175,6 +175,39 @@ pub enum NoonApiOperations { Reverse, Refund, } + +#[derive(Debug, Serialize)] +pub struct NoonRouterData<T> { + pub amount: String, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for NoonRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (currency_unit, currency, amount, router_data): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = conn_utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data, + }) + } +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonPaymentsRequest { @@ -186,10 +219,16 @@ pub struct NoonPaymentsRequest { billing: Option<NoonBilling>, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { +impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let (payment_data, currency, category) = match item.request.connector_mandate_id() { + fn try_from( + item: &NoonRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let (payment_data, currency, category) = match item + .router_data + .request + .connector_mandate_id() + { Some(subscription_identifier) => ( NoonPaymentData::Subscription(NoonSubscription { subscription_identifier, @@ -198,7 +237,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { None, ), _ => ( - match item.request.payment_method_data.clone() { + match item.router_data.request.payment_method_data.clone() { api::PaymentMethodData::Card(req_card) => Ok(NoonPaymentData::Card(NoonCard { name_on_card: req_card.card_holder_name.clone(), number_plain: req_card.card_number.clone(), @@ -242,7 +281,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { } api_models::payments::WalletData::PaypalRedirect(_) => { Ok(NoonPaymentData::PayPal(NoonPayPal { - return_url: item.request.get_router_return_url()?, + return_url: item.router_data.request.get_router_return_url()?, })) } api_models::payments::WalletData::AliPayQr(_) @@ -291,13 +330,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { }) } }?, - Some(item.request.currency), - item.request.order_category.clone(), + Some(item.router_data.request.currency), + item.router_data.request.order_category.clone(), ), }; // The description should not have leading or trailing whitespaces, also it should not have double whitespaces and a max 50 chars according to Noon's Docs let name: String = item + .router_data .get_description()? .trim() .replace(" ", " ") @@ -305,11 +345,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { .take(50) .collect(); - let ip_address = item.request.get_ip_address_as_optional(); + let ip_address = item.router_data.request.get_ip_address_as_optional(); let channel = NoonChannels::Web; let billing = item + .router_data .address .billing .clone() @@ -326,27 +367,34 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { }, }); - let (subscription, tokenize_c_c) = - match item.request.setup_future_usage.is_some().then_some(( + let (subscription, tokenize_c_c) = match item + .router_data + .request + .setup_future_usage + .is_some() + .then_some(( NoonSubscriptionData { subscription_type: NoonSubscriptionType::Unscheduled, name: name.clone(), }, true, )) { - Some((a, b)) => (Some(a), Some(b)), - None => (None, None), - }; + Some((a, b)) => (Some(a), Some(b)), + None => (None, None), + }; let order = NoonOrder { - amount: conn_utils::to_currency_base_unit(item.request.amount, item.request.currency)?, + amount: conn_utils::to_currency_base_unit( + item.router_data.request.amount, + item.router_data.request.currency, + )?, currency, channel, category, - reference: item.connector_request_reference_id.clone(), + reference: item.router_data.connector_request_reference_id.clone(), name, ip_address, }; - let payment_action = if item.request.is_auto_capture()? { + let payment_action = if item.router_data.request.is_auto_capture()? { NoonPaymentActions::Sale } else { NoonPaymentActions::Authorize @@ -357,7 +405,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { billing, configuration: NoonConfiguration { payment_action, - return_url: item.request.router_return_url.clone(), + return_url: item.router_data.request.router_return_url.clone(), tokenize_c_c, }, payment_data, @@ -598,19 +646,19 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NoonPaymentsCancelRequest { } } -impl<F> TryFrom<&types::RefundsRouterData<F>> for NoonPaymentsActionRequest { +impl<F> TryFrom<&NoonRouterData<&types::RefundsRouterData<F>>> for NoonPaymentsActionRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &NoonRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { let order = NoonActionOrder { - id: item.request.connector_transaction_id.clone(), + id: item.router_data.request.connector_transaction_id.clone(), }; let transaction = NoonActionTransaction { amount: conn_utils::to_currency_base_unit( - item.request.refund_amount, - item.request.currency, + item.router_data.request.refund_amount, + item.router_data.request.currency, )?, - currency: item.request.currency, - transaction_reference: Some(item.request.refund_id.clone()), + currency: item.router_data.request.currency, + transaction_reference: Some(item.router_data.request.refund_id.clone()), }; Ok(Self { api_operation: NoonApiOperations::Refund,
2023-11-05T11:34:36Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Addressing Issue #2237 - Modified two files in `hyperswitch/crates/router/src/connector/` - `noon.rs` - Implement `get_currency_unit` function - Modify `ConnectorIntegration` implementations for `Noon` - `noon/transformers.rs` - Implement `NoonRouterData<T>` structure and functionality - Modify implementation for `NoonPaymentsRequest` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8e484ddab8d3f4463299c7f7e8ce75b8dd628599
juspay/hyperswitch
juspay__hyperswitch-2233
Bug: [FEATURE]: [Nexi Nets] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nexinets.rs b/crates/router/src/connector/nexinets.rs index 30ae4ab25e5..ac0d7494d2d 100644 --- a/crates/router/src/connector/nexinets.rs +++ b/crates/router/src/connector/nexinets.rs @@ -76,6 +76,10 @@ impl ConnectorCommon for Nexinets { "nexinets" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -200,9 +204,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = nexinets::NexinetsPaymentsRequest::try_from(req)?; + let connector_router_data = nexinets::NexinetsRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = nexinets::NexinetsPaymentsRequest::try_from(&connector_router_data)?; let nexinets_req = types::RequestBody::log_and_get_request_body( - &req_obj, + &connector_req, utils::Encode::<nexinets::NexinetsPaymentsRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 2af3ee0a1bb..ce34fe8f5a2 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -14,7 +14,10 @@ use crate::{ consts, core::errors, services, - types::{self, api, storage::enums, transformers::ForeignFrom}, + types::{ + self, api, storage::enums, transformers::ForeignFrom, PaymentsAuthorizeData, + PaymentsResponseData, + }, }; #[derive(Debug, Serialize)] @@ -27,7 +30,6 @@ pub struct NexinetsPaymentsRequest { payment: Option<NexinetsPaymentDetails>, #[serde(rename = "async")] nexinets_async: NexinetsAsyncDetails, - merchant_order_id: Option<String>, } #[derive(Debug, Serialize, Default)] @@ -163,29 +165,70 @@ pub struct ApplepayPaymentMethod { token_type: String, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest { +#[derive(Debug, Serialize)] +pub struct NexinetsRouterData<T> { + amount: i64, + router_data: T, +} +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for NexinetsRouterData<T> +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let return_url = item.request.router_return_url.clone(); + fn try_from( + (_currency_unit, _currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + amount, + router_data: item, + }) + } +} + +impl + TryFrom< + &NexinetsRouterData< + &types::RouterData< + types::api::payments::Authorize, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + >, + > for NexinetsPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &NexinetsRouterData< + &types::RouterData< + types::api::payments::Authorize, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + >, + ) -> Result<Self, Self::Error> { + let return_url = item.router_data.request.router_return_url.clone(); let nexinets_async = NexinetsAsyncDetails { success_url: return_url.clone(), cancel_url: return_url.clone(), failure_url: return_url, }; - let (payment, product) = get_payment_details_and_product(item)?; - let merchant_order_id = match item.payment_method { - // Merchant order id is sent only in case of card payment - enums::PaymentMethod::Card => Some(item.connector_request_reference_id.clone()), - _ => None, - }; + let (payment, product) = get_payment_details_and_product(&item.router_data)?; Ok(Self { - initial_amount: item.request.amount, - currency: item.request.currency, + initial_amount: item.router_data.request.amount, + currency: item.router_data.request.currency, channel: NexinetsChannel::Ecom, product, payment, nexinets_async, - merchant_order_id, }) } } @@ -312,23 +355,12 @@ pub struct NexinetsPaymentsMetadata { } impl<F, T> - TryFrom< - types::ResponseRouterData< - F, - NexinetsPreAuthOrDebitResponse, - T, - types::PaymentsResponseData, - >, - > for types::RouterData<F, T, types::PaymentsResponseData> + TryFrom<types::ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, PaymentsResponseData>> + for types::RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - NexinetsPreAuthOrDebitResponse, - T, - types::PaymentsResponseData, - >, + item: types::ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let transaction = match item.response.transactions.first() { Some(order) => order, @@ -421,13 +453,12 @@ pub struct NexinetsPaymentResponse { pub transaction_type: NexinetsTransactionType, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, NexinetsPaymentResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<types::ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsResponseData>> + for types::RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, NexinetsPaymentResponse, T, types::PaymentsResponseData>, + item: types::ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let transaction_id = Some(item.response.transaction_id.clone()); let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata {
2023-10-25T01:48:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This pull request implements the get_currency_unit from the ConnectorCommon trait for the Nexinets connector. This function allows connectors to declare their accepted currency unit as either Base or Minor. For Nexinets it accepts currency as Minor units. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables Following are the paths where you can find config files: 1. crates/router/src/connector/nexinets.rs 2. crates/router/src/connector/nexinets/transformers.rs ## Motivation and Context Closes #2233 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> We need to create a payment using Nexinets and test the currency unit from connector response and connector 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` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
8e484ddab8d3f4463299c7f7e8ce75b8dd628599
juspay/hyperswitch
juspay__hyperswitch-2230
Bug: [FEATURE]: [Klarna] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 1814f9de809..2611c062ebe 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -32,6 +32,10 @@ impl ConnectorCommon for Klarna { "klarna" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -406,7 +410,13 @@ impl &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = klarna::KlarnaPaymentsRequest::try_from(req)?; + let connector_router_data = klarna::KlarnaRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = klarna::KlarnaPaymentsRequest::try_from(&connector_router_data)?; let klarna_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<klarna::KlarnaPaymentsRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index 3607818353a..b31d56d51b9 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -8,6 +8,37 @@ use crate::{ types::{self, storage::enums}, }; +#[derive(Debug, Serialize)] +pub struct KlarnaRouterData<T> { + amount: i64, + router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for KlarnaRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (_currency_unit, _currency, amount, router_data): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + amount, + router_data, + }) + } +} + #[derive(Default, Debug, Serialize)] pub struct KlarnaPaymentsRequest { order_lines: Vec<OrderLines>, @@ -88,10 +119,13 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<KlarnaSessionResponse>> } } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for KlarnaPaymentsRequest { +impl TryFrom<&KlarnaRouterData<&types::PaymentsAuthorizeRouterData>> for KlarnaPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let request = &item.request; + + fn try_from( + item: &KlarnaRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let request = &item.router_data.request; match request.order_details.clone() { Some(order_details) => Ok(Self { purchase_country: "US".to_string(),
2023-10-02T10:10:41Z
## Type of Change - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This pull request implements the `get_currency_unit` from the `ConnectorCommon` trait for the Klarna connector. This function allows connectors to declare their accepted currency unit as either `Base` or `Minor`. For Klarna it accepts currency as `Minor` units. ### 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). --> Fixes #2230 ## How did you test it? `cargo check`, `cargo clippy`, and `cargo test` all pass without any new errors. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
89cb63be3328010d26b5f6322449fc50e80593e4
juspay/hyperswitch
juspay__hyperswitch-2236
Bug: [FEATURE]: [NMI] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs index cdeb9c99d5e..4f7ee15d730 100644 --- a/crates/router/src/connector/nmi.rs +++ b/crates/router/src/connector/nmi.rs @@ -58,6 +58,10 @@ impl ConnectorCommon for Nmi { "nmi" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.nmi.base_url.as_ref() } @@ -210,7 +214,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = nmi::NmiPaymentsRequest::try_from(req)?; + let connector_router_data = nmi::NmiRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = nmi::NmiPaymentsRequest::try_from(&connector_router_data)?; let nmi_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<nmi::NmiPaymentsRequest>::url_encode, @@ -351,7 +361,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme &self, req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = nmi::NmiCaptureRequest::try_from(req)?; + let connector_router_data = nmi::NmiRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount_to_capture, + req, + ))?; + let connector_req = nmi::NmiCaptureRequest::try_from(&connector_router_data)?; let nmi_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<NmiCaptureRequest>::url_encode, @@ -491,7 +507,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = nmi::NmiRefundRequest::try_from(req)?; + let connector_router_data = nmi::NmiRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_req = nmi::NmiRefundRequest::try_from(&connector_router_data)?; let nmi_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<nmi::NmiRefundRequest>::url_encode, diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 582bb9f7367..995341fefd9 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -40,6 +40,37 @@ impl TryFrom<&ConnectorAuthType> for NmiAuthType { } } +#[derive(Debug, Serialize)] +pub struct NmiRouterData<T> { + pub amount: f64, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for NmiRouterData<T> +{ + type Error = Report<errors::ConnectorError>; + + fn try_from( + (_currency_unit, currency, amount, router_data): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + amount: utils::to_currency_base_unit_asf64(amount, currency)?, + router_data, + }) + } +} + #[derive(Debug, Serialize)] pub struct NmiPaymentsRequest { #[serde(rename = "type")] @@ -77,25 +108,27 @@ pub struct ApplePayData { applepay_payment_data: Secret<String>, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for NmiPaymentsRequest { +impl TryFrom<&NmiRouterData<&types::PaymentsAuthorizeRouterData>> for NmiPaymentsRequest { type Error = Error; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let transaction_type = match item.request.is_auto_capture()? { + fn try_from( + item: &NmiRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let transaction_type = match item.router_data.request.is_auto_capture()? { true => TransactionType::Sale, false => TransactionType::Auth, }; - let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; - let amount = - utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?; - let payment_method = PaymentMethod::try_from(&item.request.payment_method_data)?; + let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?; + let amount = item.amount; + let payment_method = + PaymentMethod::try_from(&item.router_data.request.payment_method_data)?; Ok(Self { transaction_type, security_key: auth_type.api_key, amount, - currency: item.request.currency, + currency: item.router_data.request.currency, payment_method, - orderid: item.connector_request_reference_id.clone(), + orderid: item.router_data.connector_request_reference_id.clone(), }) } } @@ -243,18 +276,17 @@ pub struct NmiCaptureRequest { pub amount: Option<f64>, } -impl TryFrom<&types::PaymentsCaptureRouterData> for NmiCaptureRequest { +impl TryFrom<&NmiRouterData<&types::PaymentsCaptureRouterData>> for NmiCaptureRequest { type Error = Error; - fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { - let auth = NmiAuthType::try_from(&item.connector_auth_type)?; + fn try_from( + item: &NmiRouterData<&types::PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { + let auth = NmiAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(Self { transaction_type: TransactionType::Capture, security_key: auth.api_key, - transactionid: item.request.connector_transaction_id.clone(), - amount: Some(utils::to_currency_base_unit_asf64( - item.request.amount_to_capture, - item.request.currency, - )?), + transactionid: item.router_data.request.connector_transaction_id.clone(), + amount: Some(item.amount), }) } } @@ -577,18 +609,15 @@ pub struct NmiRefundRequest { amount: f64, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for NmiRefundRequest { +impl<F> TryFrom<&NmiRouterData<&types::RefundsRouterData<F>>> for NmiRefundRequest { type Error = Error; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { - let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; + fn try_from(item: &NmiRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { + let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?; Ok(Self { transaction_type: TransactionType::Refund, security_key: auth_type.api_key, - transactionid: item.request.connector_transaction_id.clone(), - amount: utils::to_currency_base_unit_asf64( - item.request.refund_amount, - item.request.currency, - )?, + transactionid: item.router_data.request.connector_transaction_id.clone(), + amount: item.amount, }) } }
2023-10-27T09:20:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Addressing Issue: #2236 - Modified two files in `hyperswitch/crates/router/src/connector/` - `nmi.rs` - Implement `get_currency_unit` function - Modify `ConnectorIntegration` implementations for `Nmi` - `nmi/transformers.rs` - Implement `NmiRouterData<T>` structure and functionality - Modify implementation for `NmiPaymentsRequest` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> We need to create a payment using NMI and test the currency unit from connector response and connector dashboard. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
53b8fefbc2f8b58d1be7e9f35ca8b7e44e327bfb
juspay/hyperswitch
juspay__hyperswitch-2226
Bug: [FEATURE]: [Forte] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/forte.rs b/crates/router/src/connector/forte.rs index 7cc3f9f9a4e..6184b130bb6 100644 --- a/crates/router/src/connector/forte.rs +++ b/crates/router/src/connector/forte.rs @@ -82,6 +82,10 @@ impl ConnectorCommon for Forte { "forte" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -226,7 +230,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = forte::FortePaymentsRequest::try_from(req)?; + let connector_router_data = forte::ForteRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = forte::FortePaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index 83bcb2c551b..96955df244e 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -7,7 +7,10 @@ use crate::{ self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, RouterData, }, core::errors, - types::{self, api, storage::enums, transformers::ForeignFrom}, + types::{ + self, api, storage::enums, transformers::ForeignFrom, PaymentsAuthorizeData, + PaymentsResponseData, + }, }; #[derive(Debug, Serialize)] @@ -62,39 +65,80 @@ impl TryFrom<utils::CardIssuer> for ForteCardType { } } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { +#[derive(Debug, Serialize)] +pub struct ForteRouterData<T> { + amount: f64, + router_data: T, +} +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for ForteRouterData<T> +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - if item.request.currency != enums::Currency::USD { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Forte"), - ))? - } - match item.request.payment_method_data { - api_models::payments::PaymentMethodData::Card(ref ccard) => { - let action = match item.request.is_auto_capture()? { + fn try_from( + (currency_unit, currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + amount: utils::get_amount_as_f64(currency_unit, amount, currency)?, + router_data: item, + }) + } +} + +impl + TryFrom< + &ForteRouterData< + &types::RouterData< + types::api::payments::Authorize, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + >, + > for FortePaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &ForteRouterData< + &types::RouterData< + types::api::payments::Authorize, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + >, + ) -> Result<Self, Self::Error> { + match &item.router_data.request.payment_method_data { + api::PaymentMethodData::Card(card) => { + let action = match item.router_data.request.is_auto_capture()? { true => ForteAction::Sale, false => ForteAction::Authorize, }; - let card_type = ForteCardType::try_from(ccard.get_card_issuer()?)?; - let address = item.get_billing_address()?; + let card_type = ForteCardType::try_from(card.get_card_issuer()?)?; + let address = item.router_data.get_billing_address()?; let card = Card { card_type, - name_on_card: ccard + name_on_card: card .card_holder_name .clone() .unwrap_or(Secret::new("".to_string())), - account_number: ccard.card_number.clone(), - expire_month: ccard.card_exp_month.clone(), - expire_year: ccard.card_exp_year.clone(), - card_verification_value: ccard.card_cvc.clone(), + account_number: card.card_number.clone(), + expire_month: card.card_exp_month.clone(), + expire_year: card.card_exp_year.clone(), + card_verification_value: card.card_cvc.clone(), }; let billing_address = BillingAddress { first_name: address.get_first_name()?.to_owned(), last_name: address.get_last_name()?.to_owned(), }; - let authorization_amount = - utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?; + let authorization_amount = item.amount.to_owned(); Ok(Self { action, authorization_amount, @@ -255,13 +299,12 @@ pub struct ForteMeta { pub auth_id: String, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, FortePaymentsResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<types::ResponseRouterData<F, FortePaymentsResponse, T, PaymentsResponseData>> + for types::RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, FortePaymentsResponse, T, types::PaymentsResponseData>, + item: types::ResponseRouterData<F, FortePaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let response_code = item.response.response.response_code; let action = item.response.action; @@ -300,18 +343,12 @@ pub struct FortePaymentsSyncResponse { pub response: ResponseStatus, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, FortePaymentsSyncResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<types::ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsResponseData>> + for types::RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - FortePaymentsSyncResponse, - T, - types::PaymentsResponseData, - >, + item: types::ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let transaction_id = &item.response.transaction_id; Ok(Self { @@ -441,13 +478,12 @@ pub struct ForteCancelResponse { pub response: CancelResponseStatus, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, ForteCancelResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<types::ResponseRouterData<F, ForteCancelResponse, T, PaymentsResponseData>> + for types::RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, ForteCancelResponse, T, types::PaymentsResponseData>, + item: types::ResponseRouterData<F, ForteCancelResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let transaction_id = &item.response.transaction_id; Ok(Self {
2023-10-11T18:34:00Z
## 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 pull request implements the get_currency_unit from the Connector trait for the Forte connector. This function allows connectors to declare their accepted currency unit as either `Base` or `Minor`. For Forte it accepts currency as `Base` units. ### 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). -->#2226 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> We need to create a payment using Forte and test the currency unit from connector response and connector 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` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable @VedantKhairnar, could you please review this pull request
2d4f6b3fa004a3f03beaa604e2dbfe95fcbe22a6
juspay/hyperswitch
juspay__hyperswitch-2229
Bug: [FEATURE]: [IataPay] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/iatapay.rs b/crates/router/src/connector/iatapay.rs index 3a813c50cf6..4db2faa2d42 100644 --- a/crates/router/src/connector/iatapay.rs +++ b/crates/router/src/connector/iatapay.rs @@ -90,6 +90,10 @@ impl ConnectorCommon for Iatapay { "application/json" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.iatapay.base_url.as_ref() } @@ -271,7 +275,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = iatapay::IatapayPaymentsRequest::try_from(req)?; + let connector_router_data = iatapay::IatapayRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let req_obj = iatapay::IatapayPaymentsRequest::try_from(&connector_router_data)?; let iatapay_req = types::RequestBody::log_and_get_request_body( &req_obj, Encode::<iatapay::IatapayPaymentsRequest>::encode_to_string_of_json, @@ -451,7 +461,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = iatapay::IatapayRefundRequest::try_from(req)?; + let connector_router_data = iatapay::IatapayRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.payment_amount, + req, + ))?; + let req_obj = iatapay::IatapayRefundRequest::try_from(&connector_router_data)?; let iatapay_req = types::RequestBody::log_and_get_request_body( &req_obj, Encode::<iatapay::IatapayRefundRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index d4731b024c8..7cdfafc858b 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -8,7 +8,7 @@ use crate::{ connector::utils::{self, PaymentsAuthorizeRequestData, RefundsRequestData, RouterData}, core::errors, services, - types::{self, api, storage::enums}, + types::{self, api, storage::enums, PaymentsAuthorizeData}, }; // Every access token will be valid for 5 minutes. It contains grant_type and scope for different type of access, but for our usecases it should be only 'client_credentials' and 'payment' resp(as per doc) for all type of api call. @@ -26,7 +26,34 @@ impl TryFrom<&types::RefreshTokenRouterData> for IatapayAuthUpdateRequest { }) } } - +#[derive(Debug, Serialize)] +pub struct IatapayRouterData<T> { + amount: f64, + router_data: T, +} +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for IatapayRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (_currency_unit, _currency, _amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + amount: utils::to_currency_base_unit_asf64(_amount, _currency)?, + router_data: item, + }) + } +} #[derive(Debug, Deserialize)] pub struct IatapayAuthUpdateResponse { pub access_token: Secret<String>, @@ -80,10 +107,29 @@ pub struct IatapayPaymentsRequest { payer_info: Option<PayerInfo>, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest { +impl + TryFrom< + &IatapayRouterData< + &types::RouterData< + types::api::payments::Authorize, + PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + >, + > for IatapayPaymentsRequest +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let payment_method = item.payment_method; + + fn try_from( + item: &IatapayRouterData< + &types::RouterData< + types::api::payments::Authorize, + PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + >, + ) -> Result<Self, Self::Error> { + let payment_method = item.router_data.payment_method; let country = match payment_method { PaymentMethod::Upi => "IN".to_string(), @@ -97,27 +143,26 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest { | PaymentMethod::BankDebit | PaymentMethod::Reward | PaymentMethod::Voucher - | PaymentMethod::GiftCard => item.get_billing_country()?.to_string(), + | PaymentMethod::GiftCard => item.router_data.get_billing_country()?.to_string(), }; - let return_url = item.get_return_url()?; - let payer_info = match item.request.payment_method_data.clone() { + let return_url = item.router_data.get_return_url()?; + let payer_info = match item.router_data.request.payment_method_data.clone() { api::PaymentMethodData::Upi(upi_data) => upi_data.vpa_id.map(|id| PayerInfo { token_id: id.switch_strategy(), }), _ => None, }; - let amount = - utils::to_currency_base_unit_asf64(item.request.amount, item.request.currency)?; let payload = Self { - merchant_id: IatapayAuthType::try_from(&item.connector_auth_type)?.merchant_id, - merchant_payment_id: Some(item.connector_request_reference_id.clone()), - amount, - currency: item.request.currency.to_string(), + merchant_id: IatapayAuthType::try_from(&item.router_data.connector_auth_type)? + .merchant_id, + merchant_payment_id: Some(item.router_data.connector_request_reference_id.clone()), + amount: item.amount, + currency: item.router_data.request.currency.to_string(), country: country.clone(), locale: format!("en-{}", country), redirect_urls: get_redirect_url(return_url), payer_info, - notification_url: item.request.get_webhook_url()?, + notification_url: item.router_data.request.get_webhook_url()?, }; Ok(payload) } @@ -275,18 +320,19 @@ pub struct IatapayRefundRequest { pub notification_url: String, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for IatapayRefundRequest { +impl<F> TryFrom<&IatapayRouterData<&types::RefundsRouterData<F>>> for IatapayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { - let amount = - utils::to_currency_base_unit_asf64(item.request.refund_amount, item.request.currency)?; + fn try_from( + item: &IatapayRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { Ok(Self { - amount, - merchant_id: IatapayAuthType::try_from(&item.connector_auth_type)?.merchant_id, - merchant_refund_id: Some(item.request.refund_id.clone()), - currency: item.request.currency.to_string(), - bank_transfer_description: item.request.reason.clone(), - notification_url: item.request.get_webhook_url()?, + amount: item.amount, + merchant_id: IatapayAuthType::try_from(&item.router_data.connector_auth_type)? + .merchant_id, + merchant_refund_id: Some(item.router_data.request.refund_id.clone()), + currency: item.router_data.request.currency.to_string(), + bank_transfer_description: item.router_data.request.reason.clone(), + notification_url: item.router_data.request.get_webhook_url()?, }) } }
2023-10-15T07:21:50Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Addresses issue #2229 - Modified the files `hyperswitch/crates/router/src/connector/iatapay/transformers.rs` and `hyperswitch/crates/router/src/connector/iatapay.rs` - Rebased with most recent 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)? --> We need to create a payment using Iatapay and test the currency unit from connector response and connector 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` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
ca77c7ce3c6b806ff60e83725cc4e50855422037
juspay/hyperswitch
juspay__hyperswitch-2240
Bug: [FEATURE]: [OpenNode] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/opennode.rs b/crates/router/src/connector/opennode.rs index 6fad0f47205..07d33382a21 100644 --- a/crates/router/src/connector/opennode.rs +++ b/crates/router/src/connector/opennode.rs @@ -72,6 +72,10 @@ impl ConnectorCommon for Opennode { "opennode" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -169,7 +173,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = opennode::OpennodePaymentsRequest::try_from(req)?; + let connector_router_data = opennode::OpennodeRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let req_obj = opennode::OpennodePaymentsRequest::try_from(&connector_router_data)?; let opennode_req = types::RequestBody::log_and_get_request_body( &req_obj, Encode::<opennode::OpennodePaymentsRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs index b367012ca75..794fc857341 100644 --- a/crates/router/src/connector/opennode/transformers.rs +++ b/crates/router/src/connector/opennode/transformers.rs @@ -10,6 +10,37 @@ use crate::{ types::{self, api, storage::enums}, }; +#[derive(Debug, Serialize)] +pub struct OpennodeRouterData<T> { + pub amount: i64, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for OpennodeRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (_currency_unit, _currency, amount, router_data): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + Ok(Self { + amount, + router_data, + }) + } +} + //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct OpennodePaymentsRequest { @@ -22,9 +53,11 @@ pub struct OpennodePaymentsRequest { order_id: String, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpennodePaymentsRequest { +impl TryFrom<&OpennodeRouterData<&types::PaymentsAuthorizeRouterData>> for OpennodePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + fn try_from( + item: &OpennodeRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { get_crypto_specific_payment_data(item) } } @@ -146,11 +179,13 @@ pub struct OpennodeRefundRequest { pub amount: i64, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for OpennodeRefundRequest { +impl<F> TryFrom<&OpennodeRouterData<&types::RefundsRouterData<F>>> for OpennodeRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from( + item: &OpennodeRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { Ok(Self { - amount: item.request.refund_amount, + amount: item.router_data.request.refund_amount, }) } } @@ -222,14 +257,15 @@ pub struct OpennodeErrorResponse { } fn get_crypto_specific_payment_data( - item: &types::PaymentsAuthorizeRouterData, + item: &OpennodeRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<OpennodePaymentsRequest, error_stack::Report<errors::ConnectorError>> { - let amount = item.request.amount; - let currency = item.request.currency.to_string(); - let description = item.get_description()?; + let amount = item.amount; + let currency = item.router_data.request.currency.to_string(); + let description = item.router_data.get_description()?; let auto_settle = true; - let success_url = item.get_return_url()?; - let callback_url = item.request.get_webhook_url()?; + let success_url = item.router_data.get_return_url()?; + let callback_url = item.router_data.request.get_webhook_url()?; + let order_id = item.router_data.connector_request_reference_id.clone(); Ok(OpennodePaymentsRequest { amount, @@ -238,7 +274,7 @@ fn get_crypto_specific_payment_data( auto_settle, success_url, callback_url, - order_id: item.connector_request_reference_id.clone(), + order_id, }) }
2023-10-19T15:45:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Addressing Issue: #2240 - Modified two files in `hyperswitch/crates/router/src/connector/` - `opennode.rs` - Implement `get_currency_unit` function - Modify `ConnectorIntegration` implementations for `Opennode` - `opennode/transformers.rs` - Implement `OpennodeRouterData<T>` structure and functionality - Modify implementation for `OpennodePaymentsRequest` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> We need to create a payment using opennode and test the currency unit from connector response and connector dashboard. ## 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 - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
62d5727092ac482dd086ab9e814a8ba5e3011849